pc2.java
来自「nanjing university cs 的java课件。 对新手很有用。付」· Java 代码 · 共 69 行
JAVA
69 行
public class PC2 {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
}
}
class Q {
int n;
boolean valueSet = false;
synchronized int get() {
if (!valueSet){
try {
wait();
}
catch (InterruptedException e) {
}
}
System.out.println("Got:" + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n) {
if (valueSet)
try {
wait();
}
catch (InterruptedException e) {}
this.n = n;
valueSet = true;
System.out.println("Put:" + n);
notify();
}
}
class Consumer
implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, " Consumer ").start();
}
public void run() {
int i = 0;
while (true) {
q.get();
}
}
}
class Producer
implements Runnable {
Q q;
Producer(Q q) {
this.q = q;
new Thread(this, " Producer ").start();
}
public void run() {
int i = 0;
while (true) {
q.put(i++);
}
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?