您的位置:首页 > 其它

线程间通讯-------等待唤醒机制

2015-11-14 17:27 337 查看
/*
线程间通讯:
其实就是多个线程在操作同一个资源,
但是操作的动作不同
*/
class Res2
{
String name;
String sex;
boolean flag=false;
}
class Input2 implements Runnable
{
private Res2 r;
Input2(Res2 r)
{
this.r=r;
}
public void run()
{
int x=0;
while(true)
{
/*
要找一个共同的不变的对象,如果在Output2和Input2中都建立Object obj=new Object();
两者用的对象是不同的,还是解决不了之前的问题。
*/
synchronized(r)
{
if(r.flag)
try {
r.wait();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
if(x==0)
{
r.name="mike";
r.sex="man";
}
else
{
r.name="丽丽";
r.sex="女女女女女女女";
}
x=(x+1)%2;
r.flag=true;
r.notify();
}
}
}
}
class Output2 implements Runnable
{
private Res2 r;
Output2(Res2 r)
{
this.r=r;
}
public void run()
{
while(true)
{
synchronized(r)
{
if(!r.flag)
try {
r.wait();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
System.out.println(r.name+"......"+r.sex);
r.flag=false;
r.notify();
}
}
}
}
public class tongxun2 {
public static void main(String[] args) {
Res2 r=new Res2();

Input2 in=new Input2(r);
Output2 out =new Output2(r);

Thread t1=new Thread(in);
Thread t2=new Thread(out);
t1.start();
t2.start();
}
}
/*
wait;
notify();
notifyAll;

都使用在同步中,因为要对持有监视器(锁)的线程操作。
所以要使用在同步中,因为只有同步才有所。

为什么这些操作线程的方法要定义在Object类中?
因为这些方法在操作同步线程时,都必须要标示它们锁操作线程只有的锁。
只有同一个锁上的被等待线程,可以被同一个锁上的notify唤醒。
不可以对不同锁中的线程进行唤醒。
也就是说,等待和唤醒必须是同一个锁。
而锁可以是任意对象,所以可以被任意对象调用的方法定义在Object类中。
*/


结果:



进去一个,输出一个。。。。。。。。。。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: