[英]java: do not start another thread while current alive
我有方法“開始”的主線程。 此方法啟動另一個線程,該線程需要很長時間。 可以從另一個線程調用方法“ start”。 如果已經有一個正在運行並且不鎖定主線程,如何避免在“啟動”方法中創建新線程? 我嘗試使用singleThreadExecutor,但是它使任務排隊。
代碼:啟動方法:
public void start(){
// need only one active thread
// if thread alive, avoid to start another
t = new Thread( new Runnable() {
public void run() {
try {
Thread.currentThread().sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
}
簡單測試
for (int i = 0; i < 100; i++) {
Thread r = new Thread( new Runnable() {
public void run() {
Helper.getInstance().start();
}
});
r.start();
}
如果只想在當前線程繁忙時丟棄新任務,則可以使用SingleThreadExecutor並將其配置為丟棄所有溢出任務,而不是對其進行排隊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.