本文實例講述了Java線程等待用法。分享給大家供大家參考,具體如下:
線程等待
public class Hello { public static void main(String[] args) { A a = new A(); new Thread(new MyRun(a)).start(); new Thread(new MyRun1(a)).start(); }}class MyRun implements Runnable { private A a; public MyRun(A a) { this.a = a; } @Override public void run() { synchronized (a) { a.setTitle("hello"); try { a.wait(); } catch (InterruptedException e) { e.printStackTrace(); } a.setNumber(12); System.out.println(a); } }}class MyRun1 implements Runnable { private A a; public MyRun1(A a) { this.a = a; } @Override public void run() { synchronized (a) { a.setTitle("world"); a.setNumber(24); a.notifyAll(); System.out.println(a); } }}class A { private String title; private Integer number; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Integer getNumber() { return number; } public void setNumber(Integer number) { this.number = number; } @Override public String toString() { return "A{" + "title='" + title + '/'' + ", number=" + number + '}'; }}
運行輸出:
A{title='world', number=24}
A{title='world', number=12}
線程等待,obj.wait()
,會釋放當前的鎖,對象的普通方法,obj.wait(超時時間)
,表示指定時間后可以自動喚醒
線程喚醒,obj.notify()
,喚醒一個線程,obj.notifyAll()
,喚醒所以線程,obj需要和線程等待的對象一致。
wait和sleep的區別
個人認為:sleep就是一種延緩代碼執行的方法,wait是有關多線程的一些高級操作。
希望本文所述對大家java程序設計有所幫助。
新聞熱點
疑難解答
圖片精選