public class Test {
public static void main(String[] args) {
final Object obj = new Object();
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
synchronized (obj){
obj.wait();
System.out.println("t1");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
synchronized (obj){
obj.notifyAll();
System.out.println("t2");
}
}
});
t1.start();
t2.start();
}
}
结果:
t2
t1
wait()的作用是让当前线程进入等待状态,同时,wait()也会让当前线程释放它所持有的锁。“直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法”,当前线程被唤醒(进入“就绪状态”)
notify()和notifyAll()的作用,则是唤醒当前对象上的等待线程;notify()是唤醒单个线程,而notifyAll()是唤醒所有的线程。
wait(long timeout)让当前线程处于“等待(阻塞)状态”,“直到其他线程调用此对象的notify()方法或 notifyAll() 方法,或者超过指定的时间量”,当前线程被唤醒(进入“就绪状态”)。
Thread.sleep()暂停当前线程并且不释放任何锁。
举个例子如下:
public class Test {
public static void main(String[] args) {
final Object obj = new Object();
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
synchronized (obj){
obj.wait();
System.out.println("t1");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
synchronized (obj){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
obj.notifyAll();
System.out.println("t2");
}
}
});
t1.start();
t2.start();
}
}
结果:
t2
t1