詳解java線程的開始、暫停、繼續(xù)
Android項目中的一個需求:通過線程讀取文件內(nèi)容,并且可以控制線程的開始、暫停、繼續(xù),來控制讀文件。在此記錄下。
直接在主線程中,通過wait、notify、notifyAll去控制讀文件的線程(子線程),報錯:java.lang.IllegalMonitorStateException。
需要注意的幾個問題:
- 任何一個時刻,對象的控制權(quán)(monitor)只能被一個線程擁有。
- 無論是執(zhí)行對象的wait、notify還是notifyAll方法,必須保證當(dāng)前運行的線程取得了該對象的控制權(quán)(monitor)。
- 如果在沒有控制權(quán)的線程里執(zhí)行對象的以上三種方法,就會報錯java.lang.IllegalMonitorStateException。
- JVM基于多線程,默認(rèn)情況下不能保證運行時線程的時序性。
線程取得控制權(quán)的3種方法:
- 執(zhí)行對象的某個同步實例方法。
- 執(zhí)行對象對應(yīng)類的同步靜態(tài)方法。
- 執(zhí)行對該對象加同步鎖的同步塊。
這里將開始、暫停、繼續(xù)封裝在線程類中,直接調(diào)用該實例的方法就行。
public class ReadThread implements Runnable{ public Thread t; private String threadName; boolean suspended=false; public ReadThread(String threadName){ this.threadName=threadName; System.out.println("Creating " + threadName ); } public void run() { for(int i = 10; i > 0; i--) { System.out.println("Thread: " + threadName + ", " + i); // Let the thread sleep for a while. try { Thread.sleep(300); synchronized(this) { while(suspended) { wait(); } } } catch (InterruptedException e) { System.out.println("Thread " + threadName + " interrupted."); e.printStackTrace(); } System.out.println("Thread " + threadName + " exiting."); } } /** * 開始 */ public void start(){ System.out.println("Starting " + threadName ); if(t==null){ t=new Thread(this, threadName); t.start(); } } /** * 暫停 */ void suspend(){ suspended = true; } /** * 繼續(xù) */ synchronized void resume(){ suspended = false; notify(); } }
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關(guān)文章
Springboot通過run啟動web應(yīng)用的方法
這篇文章主要介紹了Springboot通過run啟動web應(yīng)用的方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-03-03解決SpringBoot連接SqlServer出現(xiàn)的問題
在嘗試通過SSL與SQL?Server建立安全連接時,如果遇到“PKIX?path?building?failed”錯誤,可能是因為未能正確配置或信任服務(wù)器證書,當(dāng)"Encrypt"屬性設(shè)置為"true"且"trustServerCertificate"屬性設(shè)置為"false"時,要求驅(qū)動程序使用安全套接字層(SSL)加密與SQL?Server建立連接2024-10-10Springboot整合Socket實現(xiàn)單點發(fā)送,廣播群發(fā),1對1,1對多實戰(zhàn)
本文主要介紹了Springboot整合Socket實現(xiàn)單點發(fā)送,廣播群發(fā),1對1,1對多實戰(zhàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08