您的位置:首页 > 其它

多线程的等待唤醒机制

2014-04-13 22:41 621 查看
一把锁一把钥匙。。就是等待跟唤醒要在同一锁内
/*
多线程的等待唤醒机制
wait();
noyify();

*/
class Pes
{
String name;
String sex;
boolean flag = false;
}
class Inp implements Runnable
{
private Pes p;
Inp(Pes p)
{
this.p = p;
}
public void run()
{
int x=0;
while(true)
{
synchronized(p){
if(p.flag)
try{p.wait();}catch(Exception e){}
if(x==0){
p.name ="nike";
p.sex = "man";
}
else
{
p.name = "mike";
p.sex = "women";
}
x= (x+1)%2;
p.flag= true;
p.notify();
}
}
}
}
class Out implements Runnable
{
private Pes p;
Out(Pes p)
{
this.p = p;
}
public void run()
{
while(true)
{
synchronized(p)
{
if(!p.flag)
try{p.wait();}catch(Exception e){}
System.out.println(p.name+"..."+p.sex);
p.flag = false;
p.notify();
}
}
}
}
class Test_12_3
{
public static void main(String[] args)
{
System.out.println("Hello Wolrd");
Pes p = new Pes();
Inp i = new Inp(p);
Out o = new Out(p);
Thread t1 = new Thread(i);
Thread t2 = new Thread(o);
t1.start();
t2.start();
}
}
//notifyAll();
/*
wait:
notify();
notifyAll();
都使用在同步中。因为要对持有监视器(锁)的线程操作。
所以要使用在同步中,因为只有同步才具有锁。
为什么这些操作线程的方法要定义Object类中呢?
因为这些方法在操作同步中线程时,都必须要标识它们所操作线程只有的锁。
只有用一个锁上的被等待线程。可以被同一个锁上notify唤醒。
不可以对不同锁中的线程进行唤醒。
也就是说。等待和唤醒必须是同一个锁
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: