線程中join()的用法


Thread中,join()方法的作用是調用線程等待該線程完成后,才能繼續用下運行。

public static void main(String[] args) throws InterruptedException
    {
        System.out.println("main start");

        Thread t1 = new Thread(new Worker("thread-1"));
        t1.start();
        t1.join();
        System.out.println("main end");
    }

在上面的例子中,main線程要等到t1線程運行結束后,才會輸出“main end”。如果不加t1.join(),main線程和t1線程是並行的。而加上t1.join(),程序就變成是順序執行了。

我們在用到join()的時候,通常都是main線程等到其他多個線程執行完畢后再繼續執行。其他多個線程之間並不需要互相等待。

下面這段代碼並沒有實現讓其他線程並發執行,線程是順序執行的。

public static void main(String[] args) throws InterruptedException
    {
        System.out.println("main start");

        Thread t1 = new Thread(new Worker("thread-1"));
        Thread t2 = new Thread(new Worker("thread-2"));
        t1.start();
        //等待t1結束,這時候t2線程並未啟動
        t1.join();
        
        //t1結束后,啟動t2線程
        t2.start();
        //等待t2結束
        t2.join();

        System.out.println("main end");
    }

為了讓t1、t2線程並行,我們可以稍微改一下代碼,下面給出完整的代碼:

public class JoinTest
{

    public static void main(String[] args) throws InterruptedException
    {
        System.out.println("main start");

        Thread t1 = new Thread(new Worker("thread-1"));
        Thread t2 = new Thread(new Worker("thread-2"));
        
        t1.start();
        t2.start();
        
        t1.join();
        t2.join();

        System.out.println("main end");
    }
}

class Worker implements Runnable
{

    private String name;

    public Worker(String name)
    {
        this.name = name;
    }

    @Override
    public void run()
    {
        for (int i = 0; i < 10; i++)
        {
            try
            {
                Thread.sleep(1l);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            System.out.println(name);
        }
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM