Java写的著名的生产者消费者问题:这里先贴上代码,后面如果需要的话加上详解
package com.jarven.thread;
public class WoTo {
private int id;
public WoTo(int id) {
this.id = id;
}
@Override
public String toString() {
return "Woto: " + id;
}
}
package com.jarven.thread;
public class SyncStack {
int index = 0; //栈顶指针
WoTo[] wtArr = new WoTo[6];
//放入
public synchronized void push(WoTo wt) {
while(index >= wtArr.length) {
try {
this.wait(); //调用该方法的线程休止
} catch(InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
wtArr[index] = wt;
index++;
}
public synchronized WoTo pop() {
while(index <= 0) {
try {
this.wait();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
index--;
return wtArr[index];
}
}
package com.jarven.thread;
public class Consumer implements Runnable {
SyncStack syncStack;
public Consumer(SyncStack syncStack) {
this.syncStack = syncStack;
}
@Override
public void run() {
for(int i=1; i<=20; i++) {
WoTo wt = syncStack.pop();
System.out.println("消费者消费---------------->" + wt);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package com.jarven.thread;
public class Producer implements Runnable {
private SyncStack syncStack;
public Producer(SyncStack syncStack) {
this.syncStack = syncStack;
}
@Override
public void run() {
for(int i=1; i<=20; i++) {
WoTo wt = new WoTo(i);
syncStack.push(wt);
System.out.println("生产者生产---------------->" + wt);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package com.jarven.thread;
public class ProducerAndConsumer {
public static void main(String[] args) {
SyncStack syncStack = new SyncStack();
Consumer c = new Consumer(syncStack);
Producer p = new Producer(syncStack);
Thread consumerThread = new Thread(c, "Consumer");
Thread producerThread = new Thread(p, "Producer");
consumerThread.start();
producerThread.start();
}
}