您的位置:首页 > 编程语言 > Java开发

JavaSE 多线程 线程间通信— 等待唤醒机制

2016-08-26 10:36 411 查看
1.1等待唤醒机制原理图



<span style="font-family:FangSong_GB2312;">package ResourceDemo2;

/*
*
* 等待唤醒机制
* 涉及的方法:
* 1.wait():让线程处于冻结状态,被wait()的线程会被存储到线程池当中。
* 2,notify():唤醒线程池中的一个线程(任意的)。
* 3,notifyAll():唤醒线程池中的所有线程。
* 这些方法都必须定义在同步中,
* 因为这些方法是用于操作线程状态的方法,
* 必须要明确到底操作的是哪个锁上的线程。
*
*
*/

class Resource{
String name;
String sex;
boolean flag=false;

}
//输入
class Input implements Runnable{
Resource r;
Input(Resource r){
this.r=r;
}
// Object obj=new Object();
public void run(){
int x=0;
while (true) {
synchronized(r){//加上同步锁
if (r.flag)
try{r.wait();}catch(InterruptedException e){}//此处不规范,后续会解决这个问题
if (x==0) {
r.name="mike";
r.sex="nan";
}else {
r.name="丽丽";
r.sex="女女女女女女";
}
r.flag=true;
r.notify();
}
x=(x+1)%2;
}
}
}

//输出
class Output implements Runnable{

Resource r;
// Object obj=new Object();
Output(Resource r){
this.r=r;
}
public void run(){
while (true){
synchronized (r){////加上同步锁(2)
if (!r.flag)
try{r.wait();}catch(InterruptedException e){}//此处不规范,后续会解决这个问题
System.out.println(r.name+"......"+r.sex);
r.flag=false;
r.notify();
}
}
}
}

public class ResourceDemo2 {
public static void main(String[] args) {
//创建资源
Resource r=new Resource();
//创建任务
Input in=new Input(r);
Output out=new Output(r);
//创建线程,执行路径
Thread t1=new Thread(in);
Thread t2=new Thread(out);
//开启线程
t1.start();
t2.start();

}
}</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐