當前位置:生活全書館 >

IT科技

> javawait使用

javawait使用

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
  • 文章版權屬於文章作者所有,轉載請註明 https://shqsg.com/dianzi/25pgpk.html