[英]Java: How to use Thread.join
我是线程的新手。 如何让t.join
工作,调用它的线程等待t执行t.join
?
这段代码只会冻结程序,因为线程正在等待自己死掉,对吧?
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);
}
如果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
}
}
Sun的Java教程: http : //java.sun.com/docs/books/tutorial/essential/concurrency/join.html
您必须在另一个Thread上调用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]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.