sleep和wait區別

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();
    }
}
相關文章
相關標籤/搜索