public class Main2 {
public static void main(String[] args) {
new Test2().start();
new Test2().start();
}
}
class Test2 extends Thread {
@Override
synchronized public void run() {
try {
System.out.println("begin wait");
wait();
} catch (Exception ex) {
}
}
}
As the actual result of running the test: start waiting, start waiting, two times from two threads. Compare with the expected result: start waiting, only once from one of the two threads, because wait () is called inside the synchronized run () method. Why can I call the Waiting for Object function () to interrupt thread synchronization?
Too much!
public class Main3 {
public static void main(String[] args) {
Test3 t = new Test3();
new Thread(t).start();
new Thread(t).start();
}
}
class Test3 implements Runnable {
synchronized public void run() {
try {
System.out.println("begin wait");
wait();
} catch (Exception ex) {
}
}
}
@akf and @Sean Owen
Thank you for your responses. Sorry for my mistake, now I changed the code to put the synchronization in the same run () object, the result is: begin wait, begin wait, two times.
@akf
wait will release the lock that the synchronization has seized and will be re-received after the stream is notified.
Could you sort it out a bit?