Java線程等待用法實例分析
本文實例講述了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的區(qū)別
個人認為:sleep就是一種延緩代碼執(zhí)行的方法,wait是有關(guān)多線程的一些高級操作。
更多java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java進程與線程操作技巧總結(jié)》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點技巧總結(jié)》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設(shè)計有所幫助。
相關(guān)文章
mybatis執(zhí)行update批量更新時報錯的解決方案
這篇文章主要介紹了mybatis執(zhí)行update批量更新時報錯的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03SpringBoot ApplicationContextAware拓展接口使用詳解
當一個類實現(xiàn)了這個接口(ApplicationContextAware)之后,這個類就可以方便獲得ApplicationContext中的所有bean。換句話說,就是這個類可以直接獲取spring配置文件中,所有有引用到的bean對象2023-04-04Struts2中Action中是否需要實現(xiàn)Execute方法
這篇文章主要介紹了Struts2中Action中是否需要實現(xiàn)Execute方法的相關(guān)資料,需要的朋友可以參考下2016-03-03springboot CompletableFuture并行計算及使用方法
CompletableFuture基于 Future 和 CompletionStage 接口,利用線程池、回調(diào)函數(shù)、異常處理、組合操作等機制,提供了強大而靈活的異步編程功能,這篇文章主要介紹了springboot CompletableFuture并行計算及使用方法,需要的朋友可以參考下2024-05-05Java日期時間處理問題(從Date、Calendar到SimpleDateFormat)
這篇文章主要介紹了Java日期時間處理深度解析(從Date、Calendar到SimpleDateFormat),我們詳細討論了Java中的日期和時間處理,包括Date、Calendar和SimpleDateFormat類的使用,以及Java?8引入的新的日期時間API的優(yōu)勢,需要的朋友可以參考下2024-08-08