我看的教程例子比較復(fù)雜,自己提取了一下,可能寫的不太好
public class ProCsum{
private static int ticket = 0;//這是臨界資源
private static boolean flag = false;//用于判斷
static ProCsum proCsum = new ProCsum();
public static void main(String[] args) {
Runnable proR = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while(ticket<6){
proCsum.produce();
}
}
};
Runnable cumR = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while(ticket<6){
proCsum.consume();
}
}
};
Thread proTh = new Thread(proR);
Thread cumPh = new Thread(cumR);
cumPh.start();
proTh.start();
}
public synchronized void produce(){
if (flag) {
//LiProductor.class.wait();
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
++ticket;
System.out.println("生產(chǎn)門票"+ticket+"號(hào)");
flag = true;
//LiProductor.class.notifyAll();
this.notifyAll();
}
public synchronized void consume(){
if (!flag) {
try {
//LiProductor.class.wait();
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("消費(fèi)門票"+ticket+"號(hào)");
flag = false;
//LiProductor.class.notifyAll();
this.notifyAll();
}
}
運(yùn)行結(jié)果:

image.png