我有一个类ThreadClass,如下所示:
public class ThreadClass extends Thread{
String msg;
public void run()
{
for(int i=0;i<=5;i++)
{
System.out.println("Run method: "+msg);
}
}
ThreadClass(String mg)
{
msg=mg;
}
}
public class MainThreadClass {
public static void main(String[] args) {
ThreadClass dt1=new ThreadClass("Thread 1");
ThreadClass dt2=new ThreadClass("Thread 2");
dt1.start();
dt2.start();
System.out.println("Finished");
}
}
我得到的输出是:
Run method: Thread 1
Finished
Run method: Thread 1
Run method: Thread 2
Run method: Thread 2
Run method: Thread 2
Run method: Thread 2
Run method: Thread 2
Run method: Thread 2
Run method: Thread 1
Run method: Thread 1
Run method: Thread 1
Run method: Thread 1
我想要实现的输出是:
Run method: Thread 1
Run method: Thread 1
Run method: Thread 2
Run method: Thread 2
Run method: Thread 2
Run method: Thread 2
Run method: Thread 2
Run method: Thread 2
Run method: Thread 1
Run method: Thread 1
Run method: Thread 1
Run method: Thread 1
Finished
因此当这两个线程终止时,打印出完成的字符串。怎么做?
答案 0 :(得分:1)
等待每个线程使用join()退出:
public class MainThreadClass {
public static void main(String[] args) {
ThreadClass dt1=new ThreadClass("Thread 1");
ThreadClass dt2=new ThreadClass("Thread 2");
dt1.start();
dt2.start();
dt1.join();
dt2.join();
System.out.println("Finished");
}
}
[抱歉糟糕的格式,出于某种原因,我无法让这看起来更好。可能是IE问题?]
答案 1 :(得分:0)
您需要确定线程何时完成:
// Create and start a thread
Thread thread = new MyThread();
thread.start();
// Check if the thread has finished in a non-blocking way
if (thread.isAlive()) {
// Thread has not finished
} else {
// Finished
}
// Wait for the thread to finish but don't wait longer than a
// specified time
long delayMillis = 5000; // 5 seconds
try {
thread.join(delayMillis);
if (thread.isAlive()) {
// Timeout occurred; thread has not finished
} else {
// Finished
}
} catch (InterruptedException e) {
// Thread was interrupted
}
// Wait indefinitely for the thread to finish
try {
thread.join();
// Finished
} catch (InterruptedException e) {
// Thread was interrupted
}
答案 2 :(得分:0)
或者使用ExecutorService。以下是我所有类似于你的课程的摘录。
ExecutorService l_service = Executors.newFixedThreadPool(l_number_threads);
List<Future<T>> l_results = null;
try {
l_results = l_service.invokeAll(a_tasks);
} catch (InterruptedException ex) {
throw ex;
}
l_service.shutdownNow();