黑马程序员--线程间的通信

来源:互联网 发布:esp8266与单片机连接 编辑:程序博客网 时间:2024/05/17 02:16
------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

一线程间通信实例

1线程间通讯:其实就是多个线程在操作同一个资源,但是操作的动作不同
2,举例

<span style="font-family:SimSun;font-size:14px;">class Resource{   private String name;   private String sex;   //在资源定义标记。   private boolean flag = false; </span>
<span style="font-family:SimSun;font-size:14px;"> </span>
<span style="font-family:SimSun;font-size:14px;">   public synchronized void set(String name,String sex)   {      if(flag)         try{this.wait();}catch(InterruptedException e){}      this.name = name;      this.sex = sex;      flag = true;      this.notify();   }    public synchronized void out()   {      if(!flag)         try{this.wait();}catch(InterruptedException e){}      System.out.println(name+"............"+sex);      flag = false;      this.notify();   }}//描述输入任务。class Input implements Runnable{   private Resource r;// private Object obj = new Object();   Input(Resource r)//线程任务一建立就必须要有处理的资源。   {      this.r = r;   }   public void run()   {      int x = 0;      while(true)      {         if(x==0)         {            r.set("nicolas","nan");         }         else         {            r.set("娇娇","女");         }              x = (x+1)%2;      }   }} //描述输出任务。class Output implements Runnable{   private Resource r ;// private Object obj = new Object();   Output(Resource r)//线程任务一建立就必须要有处理的资源。   {      this.r = r;   }   public void run()   {      while(true)      {         r.out();      }   }} class  TongXin{   public static void main(String[] args)   {      //1,创建资源的对象.      Resource r = new Resource();       //2,创建线程任务对象。      Input in = new Input(r);      Output out = new Output(r);       //3,创建线程对象。      Thread t1 = new Thread(in);      Thread t2 = new Thread(out);       //4,开启线程。      t1.start();      t2.start();   }}</span>

二线程知识

1线程间通信重要的机制:等待唤醒机制:涉及的方法:wait(),notify(),notifyAll();

2wait():可以让线程处于冻结状态,释放执行资格和执行权。同时将线程存储到一个线程池中。

3notify():只唤醒线程池中一个线程。还是任意的一个。让一个具备执行资格。

4notifyAll():唤醒线程池中所有线程。让所有线程都具备执行资格。

5这些方法都必须要使用在同步中同步可以有多个,只能用同步的锁来区分。

6这些方法必须在使用时要明确wait的是哪个锁上的线程,notify的是哪个锁上的线程。所以在使用的时候,必须要用锁对象来调用这些方法。

7为什么操作线程的方法,定义在了Object类中。

因为这些方法需要定义在同步中,明确所属锁,而锁又是任意类型的对象。

任意类型的对象可以调用的方法必须定义Object类中。

三实用Lock实现以上程序

1.JDK1.5中,提供了许多线程解决方案,将同步synchrozed 替换成 显示 Lock 操作。Object 中的 wait ,notify,notifyAll,替换成了condition 对象。

该对象可以Lock锁,进行获取。

<span style="font-family:SimSun;font-size:14px;">import java.util.concurrent.locks.*;class Resource{ private String name; private int count=1;       //在资源定义标记。   private boolean flag = false;  private Lock lock=new ReentrantLock();  private Condition condition_con=lock.newCondition();  private Condition condition_pon=lock.newCondition();    public  void set(String name) throws InterruptedException   {   lock.lock();  try{   while(flag)   {condition_pon.await();   }  this.name = name+"..,,,"+count++;  System.out.println(Thread.currentThread().getName()+";;;;;生产者"+this.name);  flag = true;  condition_con.signal();}finally    {lock.unlock();}      }    public synchronized void out() throws InterruptedException    {    lock.lock();   try   {while(!flag)condition_con.await(); System.out.println(Thread.currentThread().getName()+"消产者"+this.name);  flag = false;  condition_pon.signal();   }  finally   {lock.unlock();  }           }}//描述输入任务。class Input implements Runnable{   private Resource r;// private Object obj = new Object();   Input(Resource r)//线程任务一建立就必须要有处理的资源。   {      this.r = r;   }   public void run()   {      int x = 0;      while(true)      {  try  { r.set("商品");  }  catch (Exception e)  {  System.out.println(e.toString());  }   }   }} //描述输出任务。class Output implements Runnable{   private Resource r ;// private Object obj = new Object();   Output(Resource r)//线程任务一建立就必须要有处理的资源。   {      this.r = r;   }   public void run()   {      while(true)      {  try  { r.out();  }  catch (Exception e)  {  System.out.println(e.toString());  }              }   }} class  Tongxin2{   public static void main(String[] args)   {      //1,创建资源的对象.      Resource r = new Resource();       //2,创建线程任务对象。      Input in = new Input(r);      Output out = new Output(r);       //3,创建线程对象。      Thread t1 = new Thread(in);  Thread t2 = new Thread(in);      Thread t3 = new Thread(out);  Thread t4= new Thread(out);        //4,开启线程。      t1.start();      t2.start();  t3.start();  t4.start();   }}</span>

四停止线程

1.多线程(停止线程)

只有一种,run()方法结束。开启多线程运行,运行代码通常是循环结构,只要控制住循环,就可以让run()方法结束,也就是线程结束。

特殊情况:当线程处于冻结状态(不是运行状态),就不会读取到标记,线程就不会结束。

当没有指定的方式让冻结的线程恢复到运行状态时,需要对冻结进行清除,强制让线程恢复到运行状态,这样就可以操作标记让线程结束,Thread类提供该方法interrupt();

class StopThread implements Runnable{private boolean flag=true;int count=0;public synchronized void run(){while (flag==true){try{this.wait();}catch (Exception e){setFlag(flag);}System.out.println(Thread.currentThread().getName()+"...."+count++);}}public boolean setFlag(boolean flag){return this.flag=false;}}class Interrupt{public static void main(String[] args){Thread t1=new Thread(new StopThread());Thread t2=new Thread(new StopThread());t1.start();t2.start();int x=0;while (true ){x=x+1;if (x==60){t1.interrupt();t2.interrupt();break;}System.out.println(Thread.currentThread().getName()+"........"+x);}}}





0 0
原创粉丝点击