線程中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(),程序就變成是順序執行了。ide

咱們在用到join()的時候,一般都是main線程等到其餘多個線程執行完畢後再繼續執行。其餘多個線程之間並不須要互相等待。this

下面這段代碼並無實現讓其餘線程併發執行,線程是順序執行的。spa

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

爲了讓t一、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);
        }
    }

}
相關文章
相關標籤/搜索