`

多线程笔记

 
阅读更多

 

程序:是文件的集合能独立完成某个功能的程序

 

进程:内存正在运行的多个程序

 

线程:是一个进程里面不同的执行路径

 

线程是通过进程来共享内存的

 

和IE的差别:

IE:一个进程多个线程

谷歌:一个程序多个进程每进入一个网页都是一个进程

*************************************************

实现线程的两种方法:

第一种:

1:先定义一个类继承Thread类

Public void CCC extends Thread{

   Public void run(){

}

}

每个线程都是通过某个特定的Thread的对象所对应的run方法来完成操作的,方法run称为线程体

2:然后在Main方法中实例化对象来启动start()方法

CCC c1=new CCC();

C1.start();

第二种:

定义线程类实现runnable接口

使用Ruanable接口可以多个线程提供共享的数据

Public static Thread currentThread();获取当前线程的引用

第一步

Class runner1 implements runnable{

   Public void run(){

     …………

}

}

第二步

Runner1 rn=new runner1();

Thread th=new thread(rn);

第三种:

Class c extends TimeTask{

   Public void run(){

}

}

 

C c=new C();

Timer t=new Timer();

t.schedule(c,1000,2000);

重接口继承比较灵活,推荐能用接口用接口

 

方法调用和线程启动的区别:

方法调用:是在Main方法里调用其他类的方法是在一条主线程里运行

线程启动:是主线程和子线程同时运行

重写方法不能抛出比被重写方法中不同的遗产

 

一个比较常用的停止线程的方法

Boolean flag =ture;

Whileflag{

   Try(){

Sleep(1000);

}

}

public void shutdown(){

   flag=flase;

}

 

 

线程同步问题:

Synchronized:锁的机制表示在执行的过程中当前对象被锁定,不用被另一个线程而打断

 

子线程在访问主线程里的数据时候是向主线COPY来的

 

死锁的概念:当某个线程执行的过程中需要同时锁定两个对象而另一个线程也要锁定同时锁定两个对象,现在是1线程锁定了T1对象2线程锁定了T2对象,都要等待对方线程释放一个对象才执行,这时就出现了死锁的情况

 

使用锁对象:

//创建锁对象

Lock l =new ReenTrantLock();

//开锁

L.lock();

//解锁

l.nulock();

*************************************************

生产和消费问题:

JDK.1.7后一般用LinkedBlockingDeque 来实现

/**

 * 产品类;

 * @author Administrator

 *

 */

publicclassComputer {

  

   publicStringname;

  

   public Computer(Stringname){

     this.name=name;

   }

  

   @Override

   publicString toString(){

     returnname;

   }

  

}

/**

 * 消费类

 * @author Administrator

 *

 */

publicclassConsumerextendsThread{

  

   @Override

   publicvoid run(){

     try {

        Computercom=MainDemo.linked.take();

        System.out.println("消费了电脑:"+com);

        Thread.sleep(1000);

     } catch (InterruptedExceptione) {

        // TODO Auto-generated catch block

        e.printStackTrace();

     }

   }

  

}

 

/**

 * 生产

 * @author Administrator

 *

 */

publicclassProduceextendsThread{

  

   inti=0;

  

   @Override

   publicvoid run(){

     i++;

     Computercom=new Computer("第"+i+"台电脑");

     try {

        Thread.sleep(1000);

     } catch (InterruptedExceptione) {

        e.printStackTrace();

     }

     try {

        MainDemo.linked.put(com);

     } catch (InterruptedExceptione) {

        // TODO: handle exception

        e.printStackTrace();

     }

   }

}

 

   //存放和消费产品的仓库,使用阻塞队列,指定容量为1

   //容量:能容纳的元素个数

   //长度:存放的元素个数

  

   publicstaticLinkedBlockingDeque<Computer> linked=new

                    LinkedBlockingDeque<Computer>(1);

  

   publicstaticvoid main(String[] args) {

    

     Producep=new Produce();

     p.start();

    

     Consumerc=new Consumer();

     c.start();

    

   }

 

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics