Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
测试wait-notify方法
package com.tt;
public class Main {
public static void main(String[] args) {
Object obj = new Object();
new Thread() {
@Override
public void run() {
System.out.println(String.format("[%s] start", Thread.currentThread().getName()));
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (obj) {
obj.notifyAll();//通知其他线程中已经调用了该对象的wait方法,导致线程等待的,重新启动起来。
}
System.out.println(String.format("[%s] end", Thread.currentThread().getName()));
}
}.start();
synchronized (obj) {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(String.format("[%s] end", Thread.currentThread().getName()));
// new Thread() {
// @Override
// public void run() {
// synchronized (obj) {
// System.out.println(String.format("[%s] start", Thread.currentThread().getName()));
// try {
// obj.wait();//调用了该对象的wait方法,导致当前线程等待,知道其他线程调用该对象的notify方法,才会重新启动
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// System.out.println(String.format("[%s] end", Thread.currentThread().getName()));
// }
// }
// }.start();
// new Thread() {
// @Override
// public void run() {
// synchronized (obj) {
// System.out.println(String.format("[%s] start", Thread.currentThread().getName()));
// try {
// obj.wait();//调用了该对象的wait方法,导致当前线程等待,知道其他线程调用该对象的notify方法,才会重新启动
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// System.out.println(String.format("[%s] end", Thread.currentThread().getName()));
// }
// }
// }.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment