開心生活站

位置:首頁 > IT科技 > 

javawait使用

IT科技7.16K

wait()方法是屬於java中的一個方法,它的作用是能夠讓當前線程進入等待狀態,同時,wait()也會讓當前線程釋放它所持有的鎖。直到其他線程調用此對象的notify()方法或者notifyAll()方法,當前線程被喚醒(也就是進入“就緒狀態”)。

說明:

notify()和notifyAll()方法的作用,則是用於喚醒當前對象上的等待線程;notify()方法是喚醒單個線程,而notifyAll()是喚醒所有的線程。

javawait使用

參考範例:

 package com.citi.test.mutiplethread.demo0503;  import java.util.Date;  public class WaitTest {     public static void main(String[] args) {         ThreadA t1=new ThreadA("t1");         System.out.println("t1:"+t1);         synchronized (t1) {             try {                 //啓動線程                 System.out.println(Thread.currentThread().getName()+" start t1");                 t1.start();                 //主線程等待t1通過notify喚醒。                 System.out.println(Thread.currentThread().getName()+" wait()"+ new Date());                 t1.wait();// 不是使t1線程等待,而是當前執行wait的線程等待                 System.out.println(Thread.currentThread().getName()+" continue"+ new Date());             } catch (Exception e) {                 e.printStackTrace();             }         }     } }  class ThreadA extends Thread{     public ThreadA(String name) {         super(name);     }     @Override     public void run() {         synchronized (this) {             System.out.println("this:"+this);             try {                 Thread.sleep(2000);//使當前線程阻塞1秒             } catch (InterruptedException e) {                 // TODO Auto-generated catch block                 e.printStackTrace();             }             System.out.println(Thread.currentThread().getName()+" call notify()");             this.notify();         }     } }
標籤:javawait