如何控制多线程的执行顺序

问题描述:

        Thread thread1 = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    System.out.println(Thread.currentThread().getName() + "...." + i);
                }
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    System.out.println(Thread.currentThread().getName() + "...." + i);
                }
            }
        });
        thread1.start();
        thread2.start();

运行结果:可见多线程运行是没有顺序的

Thread-1....0
Thread-1....1
Thread-1....2
Thread-2....0
Thread-1....3
Thread-1....4
Thread-1....5
Thread-1....6

方法1:join

解释:join源码中执行的是Object类中的wait方法。原理是让主线程处于wait,知道子线程执行结束才继续执行主线程。
        thread1.start();
        thread1.join();
        thread2.start();
        thread2.join();

方法2:利用单线程池Executors.newSingleThreadExecutor()

        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(thread1);
        executor.submit(thread2);
        executor.submit(thread3);
        executor.shutdown();

猜你喜欢

转载自www.cnblogs.com/yejiang/p/12142792.html