Java:如何使用 Thread.join
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1908515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: How to use Thread.join
提问by Nick Heiner
I'm new to threads. How can I get t.join
to work, whereby the thread calling it waits until t is done executing?
我是线程的新手。我怎样才能开始t.join
工作,从而调用它的线程等待 t 完成执行?
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);
}
}
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?
如果我想要两个线程,其中一个打印出info
数组的一半,然后等待另一个完成,然后再执行其余操作,我该怎么办?
采纳答案by Francis Upton IV
Use something like this:
使用这样的东西:
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);
}
回答by user85421
You have to call the join
method on the other Thread.
Something like:
您必须join
在另一个线程上调用该方法。
就像是:
@Override
public void run() {
String[] info = new String[] {"abc", "def", "ghi", "jkl"};
Thread other = new OtherThread();
other.start();
for (int i = 0; i < info.length; i++) {
try {
if (i == info.length / 2) {
other.join(); // wait for other to terminate
}
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("%s %s%n", getName(), info[i]);
}
}
回答by Sven Lilienthal
With otherThread being the other thread, you can do something like this:
将 otherThread 作为另一个线程,您可以执行以下操作:
@Override
public void run() {
int i = 0;
int half = (info.size() / 2);
for (String s : info) {
i++;
if (i == half) {
try {
otherThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("%s %s%n", getName(), s);
Thread.yield(); //Give other threads a chance to do their work
}
}
The Java-tutorial from Sun: http://java.sun.com/docs/books/tutorial/essential/concurrency/join.html
Sun 的 Java 教程:http: //java.sun.com/docs/books/tutorial/essential/concurrency/join.html