我看的教程例子比较复杂,自己提取了一下,可能写的不太好
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("生产门票"+ticket+"号");
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("消费门票"+ticket+"号");
flag = false;
//LiProductor.class.notifyAll();
this.notifyAll();
}
}
运行结果: