1. 程式人生 > >sleep(),wait(),notify()三者的區別

sleep(),wait(),notify()三者的區別

MultiThread { public static void main(String[] args) { new Thread(new Thread1()).start(); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } new Thread(new Thread2()).start(); } private static class
Thread1 implements Runnable { public void run() { synchronized (MultiThread.class) { System.out.println("enter thread1"); System.out.println("thread1 is waiting"); try { //wait()會釋放鎖,本執行緒會進入等待鎖定池 //MultiThread.class.wait();
//sleep()不會釋放鎖, Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("thread1 is going on..."); System.out.println("thread1 is being over!"); } } } private static class
Thread2 implements Runnable { public void run() { synchronized (MultiThread.class) { System.out.println("enter thread2"); System.out.println("thread2 notify other thread can release wait status.."); //notify()不會釋放鎖,當本同步程式碼塊執行完,別的執行緒才有可能執行 MultiThread.class.notify(); System.out.println("thread2 is sleeping ten millisecond..."); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("thread2 is going on..."); System.out.println("thread2 is being over!"); } } } }