1 sleep() 定义在Thread类中,是static native方法,static 说明是属于类的,不属于对象的。java
wait()/notify()定义在Object类中,即全部类中都会有这些方法。ide
2 sleep(): 线程休眠必定时间,放弃CPU时间片;休眠结束后,等待分配CPU资源,继续执行。(并不放弃锁)this
wait(): 放弃得到的锁(即前提是已经获得了锁),等待其余线程notify。再次获得锁后,继续执行。线程
/** * Causes the currently executing thread to sleep (temporarily cease * execution) for the specified number of milliseconds, subject to * the precision and accuracy of system timers and schedulers. The thread * does not lose ownership of any monitors.//1 仍然拥有锁 */ public static native void sleep(long millis) throws InterruptedException;
public class Object { public final native void wait(long timeout) throws InterruptedException; public final native void notify(); }
public class _01_TestSleep { public static void main(String[] args) throws Exception { Task task = new Task(); System.out.println(System.currentTimeMillis()/1000 + " begin----"); Task.sleep(1000); // static方法,当前线程暂停 task.sleep(1000); // static方法,当前线程暂停 System.out.println(System.currentTimeMillis()/1000 + " over----"); } } class Task extends Thread { @Override public void run() { } }
//网上找的例子:模拟忙等待过程 class MyObject implements Runnable { private Monitor monitor; public MyObject(Monitor monitor) { this.monitor = monitor; } public void run() { try { TimeUnit.SECONDS.sleep(3); System.out.println("i'm going."); monitor.gotMessage(); } catch (InterruptedException e) { e.printStackTrace(); } } } class Monitor implements Runnable { private volatile boolean go = false; public synchronized void gotMessage() throws InterruptedException { go = true; notify(); } public synchronized void watching() throws InterruptedException { while (go == false) wait(); // 放弃锁资源,等待被唤醒, 和 while, synchronized, notify 等一块儿使用 System.out.println("He has gone."); } public void run() { try { watching(); } catch (InterruptedException e) { e.printStackTrace(); } } } public class _03_Wait { public static void main(String[] args) { Monitor monitor = new Monitor(); MyObject o = new MyObject(monitor); new Thread(o).start(); new Thread(monitor).start(); } }