多线程-线程间通信和等待唤醒

来源:互联网 发布:迅雷看看mac版 编辑:程序博客网 时间:2024/05/17 23:40

线程间通信:

不同的线程操作同一个资源。

等待/唤醒机制。 



涉及的方法:


1,wait(): 让线程处于冻结状态,被wait的线程会被存储到线程池中。
2,notify():唤醒线程池中一个线程(任意).
3,notifyAll():唤醒线程池中的所有线程。


这些方法都必须定义在同步中。
因为这些方法是用于操作线程状态的方法。
必须要明确到底操作的是哪个锁上的线程。




为什么操作线程的方法wait notify notifyAll定义在了Object类中? 


因为这些方法是监视器的方法。监视器其实就是锁。

锁可以是任意的对象,任意的对象调用的方式一定定义在Object类中。

需求:创建两个线程,线程a向资源里存数据,线程b从资源里取数据,且每存一个才取一个。

思路:

1、由于两个线程的任务不同,则不能用操作静态成员的方式。创建一个资源对象,及其所属类。

2、创建两个实现Runnable的类,用於封装不同线程的任务。

3,创建两个线程,开启两个资源。

package cm;public class ThreadMail {public static void main(String[] args) {//创建资源Resource s=new Resource();//创建任务Input in=new Input(s);Output out =new Output(s);//创建线程,执行路径Thread t=new Thread(in);Thread t1=new Thread(out);t.start();t1.start();}} class Resource{ private String name; private String sex;boolean flag=false;public synchronized void set(String name,String sex){if(flag)try {this.wait();} catch (InterruptedException e) {                  e.printStackTrace();}this.name=name;this.sex=sex;flag=!flag;this.notify();}public synchronized void out(){if(!flag)try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}System.out.println(name+"...."+sex);flag=!flag;this.notify();}}  class Input implements Runnable { Resource r;Input(Resource r){this.r=r;}public void run() {int x=0;while(true){ if(x==0){r.set("mike","male");}else{r.set("丽丽","女女女");}x=(x+1)%2;}}}class Output implements Runnable{Resource r;Output(Resource r){this.r=r;}public void run() {while(true){r.out();}}}