現在有T1、T2、T3三個線程,怎樣保證T2在T1執行完后執行,T3在T2執行完后執行?使用Join


public class TestJoin
{
    public static void main(String[] args)
    {
        Thread t1 = new MyThread("線程1");
        Thread t2 = new MyThread("線程2");
        Thread t3 = new MyThread("線程3");
        
        try
        {
            //t1先啟動
            t1.start();
            t1.join();
            //t2
            t2.start();
            t2.join();
            //t3
            t3.start();
            t3.join();
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }
}

class MyThread extend Thread{
    public MyThread(String name){
setName(name);
} @Override
public void run() { for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName()+": "+i); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }

 

還有一種方式,在t3開始前join t2,在t2開始前join t1

public class TestJoin2
{
    public static void main(String[] args)
    {
        final Thread t1 = new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println("t1");
            }
        });
        final Thread t2 = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    //引用t1線程,等待t1線程執行完
                    t1.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("t2");
            }
        });
        Thread t3 = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    //引用t2線程,等待t2線程執行完
                    t2.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("t3");
            }
        });
        t3.start();
        t2.start();
        t1.start();
    }
}

 


免責聲明!

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



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