生產(chǎn)者與消費(fèi)者問(wèn)題
package xianPack;
//生產(chǎn)者 消費(fèi)者
public class Test10 {
public static void main(String[] args) {
final Apple apple = new Apple();
//吃蘋(píng)果的人 (上下兩種方法一樣)
new Thread(new Runnable() {
public void run() {
try {
apple.eat();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
},"線程1").start();
Thread thread1 = new Thread(new Runnable() {
public void run() {
try {
apple.eat();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
},"線程2");
thread1.start();
//種蘋(píng)果的
new Thread(new Runnable() {
public void run() {
try {
apple.plant();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
},"線程3").start();
new Thread(new Runnable() {
public void run() {
try {
apple.plant();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"線程4").start();
}
}
class Apple {
int num = 0; //蘋(píng)果的數(shù)量
//吃蘋(píng)果
void eat() throws InterruptedException {
while (true) {
synchronized (this) {
if (num > 0) {
num--;
Thread thread = Thread.currentThread();
System.out.println(thread.getName() + "吃蘋(píng)果,剩下" + num);
//并且通知種蘋(píng)果的種
notifyAll();
}else { //沒(méi)有蘋(píng)果了
//進(jìn)入等待狀態(tài)
wait();
//并且通知種蘋(píng)果的種
//notify(); //通知一個(gè)
}
}
}
}
//種蘋(píng)果
void plant() throws InterruptedException {
while (true) {
//鎖放在里邊 一邊吃一邊種
synchronized (this) {
//如果生產(chǎn)大于20個(gè),停止生產(chǎn)
if (num < 20) {
this.num++;
Thread thread = Thread.currentThread();
System.err.println(thread.getName() + "種蘋(píng)果,剩下" + num);
//通知吃蘋(píng)果的吃
notifyAll(); //通知所有的
}else { //蘋(píng)果太多 不能生產(chǎn)了
//等待
wait();
}
}
}
}
}