//wait 和 notify
public class ProducerConsumerWithWaitNofity {
public static void main(String[] args) {
Resource resource = new Resource();
//生產者線程
ProducerThread p1 = new ProducerThread(resource);
ProducerThread p2 = new ProducerThread(resource);
ProducerThread p3 = new ProducerThread(resource);
//消費者線程
ConsumerThread c1 = new ConsumerThread(resource);
//ConsumerThread c2 = new ConsumerThread(resource);
//ConsumerThread c3 = new ConsumerThread(resource);
p1.start();
p2.start();
p3.start();
c1.start();
//c2.start();
//c3.start();
}
}
/**
* 公共資源類
* @author
*
*/
class Resource{//重要
//當前資源數量
private int num = 0;
//資源池中允許存放的資源數目
private int size = 10;
/**
* 從資源池中取走資源
*/
public synchronized void remove(){
if(num > 0){
num--;
System.out.println("消費者" + Thread.currentThread().getName() +
"消耗一件資源," + "當前線程池有" + num + "個");
notifyAll();//通知生產者生產資源
}else{
try {
//如果沒有資源,則消費者進入等待狀態
wait();
System.out.println("消費者" + Thread.currentThread().getName() + "線程進入等待狀態");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 向資源池中添加資源
*/
public synchronized void add(){
if(num < size){
num++;
System.out.println(Thread.currentThread().getName() + "生產一件資源,當前資源池有"
+ num + "個");
//通知等待的消費者
notifyAll();
}else{
//如果當前資源池中有10件資源
try{
wait();//生產者進入等待狀態,並釋放鎖
System.out.println(Thread.currentThread().getName()+"線程進入等待");
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
/**
* 消費者線程
*/
class ConsumerThread extends Thread{
private Resource resource;
public ConsumerThread(Resource resource){
this.resource = resource;
}
@Override
public void run() {
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
resource.remove();
}
}
}
/**
* 生產者線程
*/
class ProducerThread extends Thread{
private Resource resource;
public ProducerThread(Resource resource){
this.resource = resource;
}
@Override
public void run() {
//不斷地生產資源
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
resource.add();
}
}
}