How to control Java thread execution order has

Thread class has a join method:

  • join (): call a thread b thread the join (), this time a thread enters the blocked state, until after the completion of execution threads b, a thread before the end of the blocked state.

Here are two kinds of writing:

Written 1:

public class JoinTest {

    public static void main(String[] args) {

        Join t1 = new Join();
        Join t2 = new Join();
        Join t3 = new Join();

        t1.setName("线程1");
        t2.setName("线程2");
        t3.setName("线程3");

        t1.setPriority(Thread.MIN_PRIORITY);//1
        t2.setPriority(5);
        t3.setPriority(Thread.MAX_PRIORITY);//10

        t1.start();


        try {
            t1.join();
            System.out.println("------------------------");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        t2.start();


        try {
            t2.join();
            System.out.println("------------------------");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        t3.start();
    }
}

class Join extends Thread{

    @Override
    public void run() {
        for (int i = 1; i <=10 ; i++) {
            System.out.println(getName()+":"+i);
        }
    }
}

2 writing:

public class JoinTest {

    public static void main(String[] args) {
    
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("t1");
            }
        }, "线程1");

        Thread t2 = new Thread(() -> {
            try {
                t1.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("t2");
        }, "线程2");

        Thread t3 = new Thread("线程3") {
            @Override
            public void run() {
                try {
                    t2.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println("t3");
            }
        };

        t1.setPriority(1);
        t2.setPriority(5);
        t3.setPriority(10);

        t3.start();
        t2.start();
        t1.start();


    }

}
Released seven original articles · won praise 0 · Views 103

Guess you like

Origin blog.csdn.net/qq_42288638/article/details/103930809