![](/img/trans.png)
[英]How can I make sure a thread is completed its task,then only new Thread can start in java?
[英]Java - Start a thread when the current thread is completed
當前運行的線程退出時是否可以啟動新線程? 我為框架編寫的代碼啟動一個線程,並鎖定(而不是Java並發鎖定)文件。 我需要處理相同的文件,但是我不能這樣做,因為鎖由框架啟動的線程持有。 我的要求是一旦框架啟動的線程完成,就啟動一個新線程來處理文件
謝謝,森提爾。
您的基本代碼結構應類似於他的
public void run(){
//prepare
synchronized{
//Access File
}
//non-trivial statements
}
這是一個在另一個線程的末尾啟動第二個線程的示例:
public class TwoThreads {
public static void main(String[] args) {
class SecondThread implements Runnable {
@Override
public void run() {
System.out.println("Start of second thread");
try {
Thread.sleep(2000);
} catch (InterruptedException e) { }
System.out.println("End of second thread");
}
}
class FirstThread implements Runnable {
@Override
public void run() {
System.out.println("Start of first thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) { }
// Second thread gets launched here
new Thread(new SecondThread()).start();
System.out.println("End of first thread");
}
}
new Thread(new FirstThread()).start();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.