모니터 개체?자바는 내가 읽었
나는 이것을 내 코드에서 시도해도 작동하지 않는다.
private Object data;
private Object sync = new Object();
public static void main(String[] args) {
SimpleProducerConsumer pc = new SimpleProducerConsumer();
new Thread(pc.new Producer()).start();
new Thread(pc.new Consumer()).start();
}
public Object pop() {
try {
sync.wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println("Before");
Object d = data;
data = null;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("pop");
System.out.println("After");
sync.notify();
return d;
}
public void push(Object d) {
try {
sync.wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
data = d;
System.out.println("push");
sync.notify();
}
class Producer implements Runnable {
@Override
public void run() {
while (true) {
push(new Object());
}
}
}
class Consumer implements Runnable {
@Override
public void run() {
while (true) {
pop();
}
}
}
내 코드가 잘못되었습니다.