本文介绍了Java:如何使用 Thread.join的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是线程的新手.我怎样才能让 t.join
工作,从而调用它的线程等待 t 完成执行?
I'm new to threads. How can I get t.join
to work, whereby the thread calling it waits until t is done executing?
这段代码只会冻结程序,因为线程正在等待自己死亡,对吗?
This code would just freeze the program, because the thread is waiting for itself to die, right?
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
数组的一半,然后等待另一个完成后再做剩下的事情?
What would I do if I wanted to have two threads, one of which prints out half the info
array, then waits for the other to finish before doing the rest?
推荐答案
像这样使用:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!