Java併發:生產者與消費者經典問題(馬士兵)
阿新 • • 發佈:2019-02-02
package houy.qing.demo;
public class ProducerSummer {
public static void main(String[] args) {
SyncStack ss = new SyncStack();
new Thread(new Producer(ss)).start();
new Thread(new Consumer(ss)).start();
}
}
class WoTo{
int id;
public WoTo(int id){
this .id = id;
}
public String toString() {
return "woto :" + id;
}
}
class SyncStack{
int index = 0;
WoTo[] arrWoTo = new WoTo[6];
public synchronized void push(WoTo wt){
while (index == arrWoTo.length) {
try {
System.out.println("系統當前時間:" + System.currentTimeMillis());
this.wait(5*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("系統當前時間:" + System.currentTimeMillis());
this.notify();
arrWoTo[index] = wt;
System.out.println("生產:" + wt);
index++;
}
public synchronized WoTo pop(){
while (index == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
index--;
return arrWoTo[index];
}
}
class Producer implements Runnable{
SyncStack ss = null;
public Producer(SyncStack ss) {
this.ss = ss;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
WoTo wt = new WoTo(i);
ss.push(wt);
try {
Thread.sleep((int)Math.random()*200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable{
SyncStack ss = null;
public Consumer(SyncStack ss) {
this.ss = ss;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
WoTo wtTo = ss.pop();
System.out.println("消費:" + wtTo);
try {
Thread.sleep((int)Math.random()*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}