zoukankan      html  css  js  c++  java
  • 如何控制多线程的执行顺序

    问题描述:

            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();
    
  • 相关阅读:
    POJ 1703 Find them, Catch them
    POJ 2236 Wireless Network
    POJ 2010 Moo University
    POJ 2184 Cow Exhibition
    POJ 3280 Cheapest Palindrome
    POJ 3009 Curling 2.0
    POJ 3669 Meteor Shower
    POJ 2718 Smallest Difference
    POJ 3187 Backward Digit Sums
    POJ 3050 Hopscotch
  • 原文地址:https://www.cnblogs.com/yejiang/p/12142792.html
Copyright © 2011-2022 走看看