I read that:
Object sync = new Object();
/* inter to monitor */
try {
sync.wait();
} catch (InterruptedException ex) {
} finally {
}
/* our code*/
/* exit from monotir */
sync.notify();
is like
synchronize (sync) {
/* our code*/
}
Does it true?
I try this in my code and it doesn't work.
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();
}
}
}
What is wrong with my code?