wait-notify实例:(生产者与消费者)
public class test1 {
public static void main(String[] args)
{
Queue q=new Queue();
Productor p=new Productor(q);
Comsumer c=new Comsumer(q);
new Thread(p).start();
new Thread(c).start();
}
}
class Productor implements Runnable{
Queue q;
Productor(Queue q)
{
this.q=q;
}
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("the productor product "+i+"car");
q.put(i);
}
}
}
class Comsumer implements Runnable{
Queue q;
Comsumer(Queue q)
{
this.q=q;
}
public void run()
{
while(true)
{
System.out.println("the comsuner get "+q.get()+"car");
}
}
}
class Queue{
int value; false代表空,true代表非空;
boolean befull=false; //用一个布尔变量实现queue中空与非空的转换;
public synchronized void put(int i)
{
if(!befull) //当befull为false时执行,即空时执行;
{
value=i;
befull=true;
notify();
}
try
{
wait();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public synchronized int get()
{
if(!befull) //同上,是当befull为false时执行;
{
try
{
wait();
}
catch(Exception e)
{
e.printStackTrace();
}
}
befull=false;
notify();
return value;
}
}
注意:(1)wait-notify方法只能在同步方法或同步块中运行
(2)二者锁定的对象必须相同,默认锁定对象为this(即当前运行的对象)
多线程(二)wait-notify实例
最新推荐文章于 2024-11-03 17:33:22 发布