Java:如何使用 Thread.join

2022-09-03 06:28:15

我是线程的新手。我怎样才能开始工作,由此调用它的线程等到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


答案 1

使用类似如下的内容:

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

答案 2

使用 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


推荐