我是线程的新手。我怎样才能让 t.join
工作,调用它的线程会一直等到 t 执行完毕?
这段代码只会卡住程序,因为线程正在等待自己死亡,对吧?
public static void main(String[] args) throws InterruptedException {
Thread t0 = new Thready();
t0.start();
}
@Override
public void run() {
for (String s : info) {
try {
join();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("%s %s%n", getName(), s);
}
}
如果我想有两个线程,其中一个打印出 info
数组的一半,然后等待另一个线程完成,然后再做剩下的,我该怎么办?
最佳答案
使用这样的东西:
public void executeMultiThread(int numThreads)
throws Exception
{
List threads = new ArrayList();
for (int i = 0; i < numThreads; i++)
{
Thread t = new Thread(new Runnable()
{
public void run()
{
// do your work
}
});
// System.out.println("STARTING: " + t);
t.start();
threads.add(t);
}
for (int i = 0; i < threads.size(); i++)
{
// Big number to wait so this can be debugged
// System.out.println("JOINING: " + threads.get(i));
((Thread)threads.get(i)).join(1000000);
}
关于Java:如何使用 Thread.join,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1908515/