首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Java:如何使用Thread.join

Java:如何使用Thread.join
EN

Stack Overflow用户
提问于 2009-12-16 00:11:19
回答 3查看 51.7K关注 0票数 16

我是线程新手。我如何才能让t.join工作,让调用它的线程等待,直到t完成执行?

这段代码只会冻结程序,因为线程正在等待自己的死亡,对吧?

代码语言:javascript
复制
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数组,然后等待另一个线程完成,然后再执行其余的操作,我该怎么办?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2009-12-16 00:19:12

使用类似如下的内容:

代码语言:javascript
复制
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);
    }
票数 17
EN

Stack Overflow用户

发布于 2009-12-16 18:56:18

使用otherThread作为另一个线程,您可以执行以下操作:

代码语言:javascript
复制
@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

票数 4
EN

Stack Overflow用户

发布于 2009-12-16 01:46:16

您必须在另一个线程上调用join方法。

类似于:

代码语言:javascript
复制
@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]);
    }       
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1908515

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档