为什么在同一类锁上等待并通知函数不能正常工作?
请参阅以下检查代码,了解等待和通知功能及其输出.
输出:
Thread-1
Thread-2
Thread-2 after notify
Run Code Online (Sandbox Code Playgroud)
预期结果:
Thread-1
Thread-2
Thread-2 after notify
Thread-1 after wait
Run Code Online (Sandbox Code Playgroud)
码:
public class WaitAndNotify1 {
public static void main(String[] args) {
Thread t1=new Thread(new Runnable(){
@Override
public void run(){
System.out.println("Thread-1");
try {
synchronized (this) {
wait();
System.out.println("Thread-1 after wait");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t2=new Thread(new Runnable(){
@Override
public void run(){
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread-2");
synchronized (this) {
notify();
System.out.println("Thread-2 …Run Code Online (Sandbox Code Playgroud)