Java:如何使用Thread.join

16

我对线程不太了解。如何使用 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数组,然后等待另一个完成后再执行剩余部分,我该怎么做呢?

3个回答

17

可以使用以下内容:

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);
    }

4

如果有另一个线程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
    }       
}

Java教程来自Sun:http://java.sun.com/docs/books/tutorial/essential/concurrency/join.html。该教程涉及Java并发编程的内容,可以帮助您更好地理解和应用Java技术。

0
你需要在另一个线程上调用 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]);
    }       
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接