在一个线程中通过一个对象来获得锁,调用wait()函数,线程进入阻塞状态。
另一个线程通过也锁定此对象,调用对象的notify()方法通知其中给一个调用wait的对象结束等待状态。如果是调用notifyAll()通知的是前面所有调用此对象wait()方法的线程继续执行。
测试代码:
代码语言:javascript复制public class ObjectNotifyTestMain {
public static void main(String[] args) {
testNotify();
testNotifyAll();
}
private static void testNotifyAll() {
Object obj = new Object();
Thread thread1 = new Thread(() -> {
synchronized (obj) {
try {
System.out.println(Thread.currentThread().getName() " - start");
obj.wait();
System.out.println(Thread.currentThread().getName() " - resume");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread2 = new Thread(() -> {
synchronized (obj) {
try {
System.out.println(Thread.currentThread().getName() " - start");
obj.wait();
System.out.println(Thread.currentThread().getName() " - resume");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread1.start();
thread2.start();
try {
Thread.sleep(100);
synchronized (obj) {
obj.notifyAll();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void testNotify() {
Object obj = new Object();
Thread thread1 = new Thread(() -> {
synchronized (obj) {
try {
System.out.println(Thread.currentThread().getName() " - start");
obj.wait();
System.out.println(Thread.currentThread().getName() " - resume");
obj.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread2 = new Thread(() -> {
synchronized (obj) {
System.out.println(Thread.currentThread().getName() " - start");
obj.notify();
try {
obj.wait();
System.out.println(Thread.currentThread().getName() " - resume");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread1.start();
thread2.start();
}
}