我有2個嵌套的線程。在一些子線程完成之前,如何讓一個Java線程返回?
第一個線程啓動第二個線程的多個實例。每個第二線程必須睡眠一段時間(5秒)。
我想開始第一個線程並立即向用戶返回一條消息,但似乎我的第一個線程一直等到第二個線程的所有子節點完成。
我該如何做到這一點?任何幫助?
我有2個嵌套的線程。在一些子線程完成之前,如何讓一個Java線程返回?
第一個線程啓動第二個線程的多個實例。每個第二線程必須睡眠一段時間(5秒)。
我想開始第一個線程並立即向用戶返回一條消息,但似乎我的第一個線程一直等到第二個線程的所有子節點完成。
我該如何做到這一點?任何幫助?
查看代碼可能會有幫助。這取決於你在哪裏放Thread.sleep();
。
處理java.lang.Thread
時有一些常見錯誤。
run
而不是start
。這對於run
方法來說並不神奇。Thread.sleep
。 sleep
是一種靜態方法,即使代碼似乎在不同的線程上調用它,它也會始終睡眠當前線程。不是直接處理線程,而是使用java.util.concurrent
的線程池。
像其他人一樣,用線程指出你調用start()這是一個非阻塞的調用,並且實際上獲得了線程的滾動。調用run()會阻塞,直到run()方法結束。請參閱下面的示例代碼;
public class Application {
public static void main(String[] args) {
FirstThread firstThread = new FirstThread();
firstThread.start();
System.out.println("Main Method ending");
}
}
public class FirstThread extends Thread {
public void run() {
for(int i = 0; i < 3; i++) {
SecondThread secondThread = new SecondThread(i);
secondThread.start();
}
System.out.println("FirstThread is finishing");
}
}
public class SecondThread extends Thread {
private int i;
public SecondThread(int i) {
this.i = i;
}
public void run() {
while(true) {
System.out.println("Second thread number " + i + " doing stuff here...");
// Do stuff here...
try {
Thread.sleep(5000);
}
catch(InterruptedException ex){
//ignore for sleeping}
}
}
}
}
它產生的輸出:
Main Method ending
Second thread number 0 doing stuff here...
Second thread number 1 doing stuff here...
FirstThread is finishing
Second thread number 2 doing stuff here...
Second thread number 0 doing stuff here...
Second thread number 2 doing stuff here...
Second thread number 1 doing stuff here...
順便說一句 - 我懷疑你實際上並不需要一個名爲「FirstThread」的類 - 你可能只需從主線程啓動SecondThread實例即可。 – 2009-11-27 01:49:24
你應該做的,是通過Executors.newCachedThreadPool()
創建一個單獨的線程池。從您的主線程submit
可運行(任務)到池中。返回主線程Future
s的列表。
在Java中,有足夠的框架代碼,很少需要直接處理線程。
我在第一個線程和第二個線程中都用'start'替換了'run'。 現在工作正常。
感謝所有回答有價值的建議。
可以使用Synchronized
關鍵字將用於運行一個線程完全
例如
public synchronized void run() //which thread to run completely
{
}
public class FirstThread extends Thread {
public synchronized void run() {
for(int i = 0; i < 3; i++) {
System.out.println("i="+i);
}
System.out.println("FirstThread is finishing");
}
}
public class SecondThread extends Thread {
public synchronized void run() {
for(int j = 0; j < 3; i++) {
System.out.println("j="+j);
}
System.out.println("Second Thread is finishing");
}
}
public class Application {
public static void main(String[] args) {
FirstThread firstThread = new FirstThread();
SecondThread a=new SecondThread()
firstThread.start();
a.start();
}
}
輸出將是:
i=0
i=1
i=2
i=3
FirstThread is finishing
j=0
j=1
j=2
j=3
Second Thread is finishing
您正在使用的代碼會可能有幫助。 – 2009-11-27 00:41:11
你在調用'Thread.run'而不是'Thread.start'嗎?這是一個非常常見的錯誤(並且是'Thread'的糟糕設計的結果)。 – 2009-11-27 00:47:40
嗨湯姆, 感謝您的答覆。 這是我的代碼的外觀。 FirstThread.run(); 在第一個線程的運行方法中,我運行了多個第二個線程,如下所示: SecondThread.run(); SecondThread.sleep(5000); 我希望我的第一個線程立即返回,而不是等待所有第二個線程子節點完成。 你建議在第一個線程或第二個線程上使用'start'? 再次感謝。 – Jani 2009-11-27 01:01:28