任何人都可以分享java生产者消费者计划的代码片段。该计划的目标是在给定的时间点应该只有1个项目。我知道我应该使用wait并通知但是无法获得完整的代码片段。这可以在不使用任何数据结构的情况下完成吗?
提前致谢。
class Consumer extends Thread {
private Good gObj;
Consumer(Good g) {
gObj = g;
}
public void run() {
synchronized(gObj) {
wait();
}
}
}
class Good { }
public class Producer implements Runnable {
private Good gObj;
Producer(Good g) {
gObj = g;
}
public void run() {
synchronized(gObj) {
notify();
}
}
public static void main(String[] args) {
Good g = new Good();
Producer p = new Producer(g);
Thread producerThread = new Thread(p);
producerThread.start();
Consumer c = new Consumer(g);
c.start();
}
}
答案 0 :(得分:0)
class Producer { String producer = "once";
/// returns the string and sets it to null
//
String get() {
String get = producer;
producer = null;
return get;
}
}
class Consumer { Producer p = new Producer();
Consumer() {
out.println( "The value of producer is: " + p.get();
out.println( "The value of producer is: " + p.get();
}
}
这可以在不使用任何数据结构的情况下完成吗?
肯定的!