Java:如何使用 Thread.join

标签 java concurrency join multithreading

我是线程的新手。我怎样才能让 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 数组的一半,然后等待另一个线程完成,然后再做剩下的,我该怎么办?

最佳答案

使用这样的东西:

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,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1908515/

相关文章:

java - 具有 SPDY 功能的 Jetty 9 的 Maven 依赖项是什么?

c# - 是否可以在后台线程上创建一个对象而不在主线程上引用?

sql-server - 两个值之间的内连接

mysql - 从两个表中获取唯一数据

php - Laravel - 加入具有复合主键的表

java - 将冒泡排序与可比较的 ArrayList 一起使用

java - @AfterClass 在 cucumber 脚本中不起作用

java - 如何在abstractDAO中使用特定的rowmapper

java - 同时查看当前时间

java - 如何使用 java 信号量实现这种并发情况?