Java中wait()和sleep()方法的區別

 public class ThreadDemo{
   public static void main(String[] args) {
        new Thread(new Thread1()).start();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
        }
        new Thread(new Thread2()).start();
    }

    private static class Thread1 implements Runnable {
        @Override
        public void run() {
            synchronized (ThreadDemo.class) {
                System.out.println("enter thread1 ...");
                System.out.println("thread1 is waiting ...");
                try {
                    //wait()方法會釋放對象鎖,該鎖進入等待隊列
                    ThreadDemo.class.wait();
                }catch (Exception e) {
                }

                System.out.println("thread1 is going on ...");
                System.out.println("thread1 is over!!!");
            }
        }
    }

    private static class Thread2 implements Runnable {
        @Override
        public void run() {
            synchronized (TaskController.class) {
                System.out.println("enter thread2 ...");
                System.out.println("thread2 is sleep ...");

                //notify()方法將線程放入等待獲取鎖的線程池中,如果沒有此方法,thread1會進入掛起狀態
                TaskController.class.notify();
                try {
                    /**
                     * sleep方法導致程序暫停執行指定的時間,讓出cpu給其他線程
                     * 但是不會釋放對象鎖,當指定的時間到了又會自動恢復到運行狀態
                     */
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                }
                System.out.println("thread2 is going on ...");
                System.out.println("thread2 is over!!!");
            }
        }
    }
 }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章