Skip to content

Instantly share code, notes, and snippets.

@guohai
Created August 24, 2011 07:25
Show Gist options
  • Save guohai/1167487 to your computer and use it in GitHub Desktop.
Save guohai/1167487 to your computer and use it in GitHub Desktop.
Thread sleep wait notify notifyAll
public class ThreadWaitSleepDemo {
public static void main(String[] args) {
// wait,notify,notifyAll三个方法都有共同点
// The current thread must own this object's monitor.
ThreadWaitSleepDemo obj = new ThreadWaitSleepDemo();
new S(obj).start();
try {
synchronized (obj) {
obj.wait(); // 可以被唤醒或者超时自动醒来
// Thread.sleep(10 * 1000); // 睡眠的线程无法唤醒,只有超时自动醒来
// Thread.sleep(0);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("i'm awaken!");
}
public void wakeMe() {
this.notify(); // 这是随机的唤醒一个线程,最好用notifyAll,处于该条件的线程都会唤醒,然后有“机会”继续执行
}
}
class S extends Thread {
ThreadWaitSleepDemo obj;
S(ThreadWaitSleepDemo obj) {
this.obj = obj;
}
public void run() {
ThreadWaitSleepDemo obj = this.obj;
try {
Thread.sleep(3 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (obj) {
obj.wakeMe();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment