这三个方法用于线程同步方法内:
1、wait可以让当前线程释放持有的锁,并让线程处于wait状态
2、notify随机唤醒之前持有该锁对象的处于wait状态的线程,让其加入锁的竞争(不会马上获得锁)
3、notifyAll唤醒所有的之前持有该锁对象的处于wait状态的线程,让其加入锁的竞争(不会马上获得锁)
所谓唤醒线程,另一种解释可以说是将线程由等待池移动到锁池,notifyAll调用后,会将全部线程由等待池移到锁池,然后参与锁的竞争,竞争成功则继续执行,如果不成功则留在锁池等待锁被释放后再次参与竞争。而notify只会唤醒一个线程。
举个例子
public class LockDemo{
/**
* 静态对象锁
*/
private static final Object SYNCHRONIZED_OBJECT = new Object();
public void method1() {
synchronized (SYNCHRONIZED_OBJECT) {
System.out.println("method1 start");
for (int i=1;i<=4;i++) {
System.out.println("method1:"+i);
try {
if (i==2) {
SYNCHRONIZED_OBJECT.notifyAll();
}
Thread.sleep(1000);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
System.out.println("method1 end");
}
}
public void method2() {
synchronized (SYNCHRONIZED_OBJECT) {
System.out.println("method2 start");
for (int i=1;i<=4;i++) {
System.out.println("method2:"+i);
try {
if (i==3) {
SYNCHRONIZED_OBJECT.wait();
}
Thread.sleep(1000);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
System.out.println("method2 end");
}
}
}
@Test
public void test1() {
LockDemo lockDemo1 = new LockDemo();
LockDemo lockDemo2 = new LockDemo();
ThreadDemo demo1 = new ThreadDemo(lockDemo1,"method1");
ThreadDemo demo2 = new ThreadDemo(lockDemo2,"method2");
demo2.start();
demo1.start();
try {
demo1.join();
demo2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
运行结果
method2 start
method2:1
method2:2
method2:3
method1 start
method1:1
method1:2
method1:3
method1:4
method1 end
method2:4
method2 end