class ProducerConsumerDemo
{
public static void main(String[] args)
{
Resource r = new Resource();
Producer pro = new Producer(r);
Consumer con = new Consumer(r);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(pro);
Thread t3 = new Thread(con);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Resource
{
private String name;
private int count = 1;
private boolean flag = false;
public synchronized void set(String name)
{
while(flag)try{wait();}catch(Exception e){}//为什么在这里如果t1运行接受后唤醒的是t2而不是t3,t4
this.name = name+"--"+count++;
System.out.println(Thread.currentThread().getName()+"....生产者...."+this.name);
flag = true;
this.notifyAll();
}
public synchronized void out()
{
while(!flag)try{wait();}catch(Exception e){}
class ProducerConsumerDemo
{
public static void main(String[] args)
{
Resource r = new Resource();
Producer pro = new Producer(r);
Consumer con = new Consumer(r);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(pro);
Thread t3 = new Thread(con);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Resource
{
private String name;
private int count = 1;
private boolean flag = false;
public synchronized void set(String name)
{
while(flag)try{wait();}catch(Exception e){}//老师的视频里面有解释的,notify唤醒的是下一个等待的线程,t2就是下一个等待唤醒的线程
this.name = name+"--"+count++;
System.out.println(Thread.currentThread().getName()+"....生产者...."+this.name);
flag = true;
this.notifyAll();
}
public synchronized void out()
{
while(!flag)try{wait();}catch(Exception e){}