/*
生產者,消費者。單生產,單消費。
*/
class Resource
{
private String name;
private int count=1;
private boolean flag = false;
public synchronized void set(String name)
{
if (flag)
try{wait();}catch(InterruptedException e){}
this.name = name +count;
count++;
System.out.println(Thread.currentThread().getName()+"...生產者...."+this.name);
flag = true;
notify();
}
public synchronized void out()
{
if (!flag)
try{wait();}catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+".........消費者.........."+this.name);
flag = false;
notify();
}
}
class Producer implements Runnable
{
private Resource r;
Producer(Resource r)
{
this.r=r;
}
public void run()
{
while (true)
{
r.set("饅頭");
}
}
}
class Consumer implements Runnable
{
private Resource r;
Consumer(Resource r)
{
this.r=r;
}
public void run()
{
while (true)
{
r.out();
}
}
}
class ProducerConsumerDemo
{
public static void main(String[] args)
{
Resource r = new Resource();
Producer pro = new Producer(r);
Consumer con = new Consumer(r);
Thread th1 = new Thread(con);
Thread th2 = new Thread(pro);
th1.start();
th2.start();
}
}
/*
生產者,消費者
多生產多消費問題。
其中繼續使用單生產,單消費中的if判斷語句的話,當有線程在wait後被notify後會直接執行生產任務(因爲被wait後的線程在線程池中,notify後不會判斷if)
所以此時就使用while判斷。while解決了notify的線程不會往上執行判斷語句。
但是如果當四個線程中三個都已經wait。最後一個線程執行notify(因爲是隨機的)被喚醒的是自己本方的線程,那麼線程會在執行一次生產或者消費任務後繼續wait。
這就造成死鎖。解決辦法就是每次都是喚醒notifyAll()。
*/
class Resource
{
private String name;
private int count=1;
private boolean flag = false;
public synchronized void set(String name)
{
while (flag)
try{wait();}catch(InterruptedException e){}
this.name = name +count;
count++;
System.out.println(Thread.currentThread().getName()+"...生產者...."+this.name);
flag = true;
notifyAll();
}
public synchronized void out()
{
while (!flag)
try{wait();}catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+".........消費者.........."+this.name);
flag = false;
notifyAll();
}
}
class Producer implements Runnable
{
private Resource r;
Producer(Resource r)
{
this.r=r;
}
public void run()
{
while (true)
{
r.set("饅頭");
}
}
}
class Consumer implements Runnable
{
private Resource r;
Consumer(Resource r)
{
this.r=r;
}
public void run()
{
while (true)
{
r.out();
}
}
}
class ProducerConsumerDemo
{
public static void main(String[] args)
{
Resource r = new Resource();
Producer pro = new Producer(r);
Consumer con = new Consumer(r);
Thread th0 = new Thread(pro);
Thread th1 = new Thread(con);
Thread th2 = new Thread(pro);
Thread th3 = new Thread(con);
th0.start();
th1.start();
th2.start();
th3.start();
}
}