生産者
public class Cooker implements Runnable{
private String name;
private Disk disk;
private String foods[];
private final Random random=new Random();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Disk getDisk() {
return disk;
}
public void setDisk(Disk disk) {
this.disk = disk;
}
public String[] getFoods() {
return foods;
}
public void setFoods(String[] foods) {
this.foods = foods;
}
public Cooker(String name, Disk disk) {
this.name = name;
this.disk = disk;
foods=new String[]{"馍馍","巧克力","可樂","莴筍","壓抑"};
}
@Override
public void run() {
for (int i = 0; i < 30; i++) {
make();
}
}
/**
* 生産
*/
public void make(){
synchronized (disk) {
if (disk.isEmpty()) {
int index=random.nextInt(foods.length);
String f=foods[index];
disk.setFood(f);
System.out.println(name+"制作了"+f);
disk.setEmpty(false);
disk.notify(); //先喚醒
try {
Thread.sleep(2000);
disk.wait();//再挂起
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
try {
disk.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
消費者
public class Custom implements Runnable{
private String name;
private Disk disk;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Disk getDisk() {
return disk;
}
public void setDisk(Disk disk) {
this.disk = disk;
}
@Override
public void run() {
//循環
while (true) {
eat();
}
}
public Custom(String name, Disk disk) {
this.name = name;
this.disk = disk;
}
public void eat(){
synchronized (disk) {
if (!disk.isEmpty()) {
String foods=disk.getFood();
System.out.println(name+"正在享受"+foods);
disk.setEmpty(true);
disk.notify(); //喚醒廚師
try {
Thread.sleep(2000);
disk.wait(); //挂起自己
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
//如果消費者先搶到線程
try {
disk.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //
}
}
}
}
中間代理
public class Disk {
private String food;
private boolean empty; //是否為空
public String getFood() {
return food;
}
public void setFood(String food) {
this.food = food;
}
public boolean isEmpty() {
return empty;
}
public void setEmpty(boolean empty) {
this.empty = empty;
}
public Disk() {
empty=true;
}
}
Main方法:
public class Test {
public static void main(String[] args) {
Disk disk=new Disk();
Cooker c=new Cooker("小廚",disk);
Custom l=new Custom("吃貨",disk);
Thread cot=new Thread(c);
Thread cut= new Thread(l);
cut.setDaemon(true);// 背景線程 ,隻要所有線程結束,這個線程就自動結束
cot.start();
cut.start();
}
}
用到的方法:wait挂起 挂線上程池中 需要notify喚醒notify() 必須在同步塊中,而經常看到的問題sleep和wait方法差別,就很簡單了,sleep休眠時間到了會自動啟用,而wait需要notify喚醒。