package thread;
public class Producer_ConsumerTest {
public static void main(String[] args) {
SyncStack ss = new SyncStack();
Thread producter = new Producter(ss);
Thread consumer = new Consumer(ss);
producter.start();
consumer.start();
}
}
class SyncStack {
private int total = 0;
private boolean flag = false;
synchronized void product() {
while(flag == true) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
total++;
flag = true;
this.notify();
}
synchronized int conmuse() {
while(flag == false) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
total--;
flag = false;
this.notify();
return total;
}
}
class Producter extends Thread {
SyncStack ss;
Producter(SyncStack ss) {
this.ss = ss;
}
public void run() {
for(int i=1;i<10;i++) {
ss.product();
System.out.println("生产者" + Thread.currentThread().getName() + "生产了第" + i + "个商品,商品总数为");
}
}
}
class Consumer extends Thread {
SyncStack ss;
Consumer(SyncStack ss) {
this.ss = ss;
}
public void run() {
for(int i=1;i<10;i++) {
ss.conmuse();
System.out.println("消费者" + Thread.currentThread().getName() + "消费了第" + i + "个商品总数为");
}
}
}
[b]我希望的输出结果是生产1个,然后消费1个,生产在前,但是达不到要求,目前实际输出是无序的,哪位朋友能帮忙修改一下吗?[/b]