sleep是线程类(Thread)的方法,导致此线程暂停执行指定时间(Thread.sleep(1000)),把执行机会给其它线程,但监控状态依然保持,到时候自动恢复;调用sleep不会释放对象锁。
wait是Object类的方法,对此对象调用wait方法导致本线程放弃对象锁,进入等待此对象的等待锁定池,只有针对此对象发出notify方法(或notifyAll)后本线程才进入对象锁定池准备获得对象锁进入运行状态。
9
9
10
10
8
8
10
10
8
8
9
9
8
wait是Object类的方法,对此对象调用wait方法导致本线程放弃对象锁,进入等待此对象的等待锁定池,只有针对此对象发出notify方法(或notifyAll)后本线程才进入对象锁定池准备获得对象锁进入运行状态。
- public class Test {
- public static void main(String[] args) {
- new TestThread().start();
- new TestThread().start();
- new TestThread().start();
- }
- }
- class TestThread extends Thread {
- private static Object lock = new Object();
- public void run() {
- while (true) {
- try {
- Thread.sleep(1);
- } catch (Exception ex) {}
- synchronized (lock) {
- System.out.println(this.getId());
- try {
- notifyAll();
- this.wait();
- try {
- Thread.sleep(1);
- } catch (Exception ex) {}
- } catch (Exception ex) {}
- System.out.println(this.getId());
- }
- }
- }
- }
public class Test {
public static void main(String[] args) {
new TestThread().start();
new TestThread().start();
new TestThread().start();
}
}
class TestThread extends Thread {
private static Object lock = new Object();
public void run() {
while (true) {
try {
Thread.sleep(1);
} catch (Exception ex) {}
synchronized (lock) {
System.out.println(this.getId());
try {
notifyAll();
this.wait();
try {
Thread.sleep(1);
} catch (Exception ex) {}
} catch (Exception ex) {}
System.out.println(this.getId());
}
}
}
}
输出
9
9
10
10
8
8
10
10
8
8
9
9
8