控制线程的执行顺序

最近看到很多人在问这样一个线程问题:现在有A1,A2,A3三个线程,正常情况下他们的执行顺序是没有规律的,然而现在我们想要的是他们要按照我们要求的顺序来执行,比如A1——>A2——>A3这样一个执行顺序;该怎么实现?说到这里,固然想到用 join()方法;话不多说,直接上代码:

/**
 * 控制线程的执行顺序
 * 
 * @author zhaoheng
 *
 */
public class Text1 {

    public static void main(String[] args) throws InterruptedException {
        // 创建线程1
        final Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程---1");

            }
        });
        // 创建线程2
        final Thread thread2 = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    // 该方法使运行状态的线程2编程阻塞态
                    thread1.join();
                } catch (InterruptedException e) {

                    e.printStackTrace();
                }
                System.out.println("线程---2");

            }
        });

        final Thread thread3 = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    // 该方法使运行状态的线程3编程阻塞态
                    thread2.join();
                } catch (InterruptedException e) {

                    e.printStackTrace();
                }
                System.out.println("线程---3");

            }
        });

        // 启动线程
        thread1.start();
        thread2.start();
        thread3.start();

    }

}

运行结果

线程---1
线程---2
线程---3

join()方法是可阻断运行态的线程的,使正在运行的线程由运行态转变为阻塞态然后运行插入的线程,当插入的线程运行之后,再运行被阻塞的线程,这样就做到了控制线程的执行顺序。

猜你喜欢

转载自blog.csdn.net/muscleheng/article/details/77978391