如何控制多線程執行順序

    static Thread thread1 = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("線程1");
        }
    });

    static Thread thread2 = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("線程2");
        }
    });

    static Thread thread3 = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("線程3");
        }
    });

執行結果:
在這裏插入圖片描述
正常執行多個線程的話,每個線程的執行順序都是隨機的,這裏我們用兩種方式來控制一下每個線程的執行順序。

方式一:
join();
通過join方法保證多線程的順序性的特性
Join:讓主線程等待子線程結束以後才能繼續運行。

thread1.start();
thread1.join();
thread2.start();
thread2.join();
thread3.start();
thread3.join();

執行流程圖:
在這裏插入圖片描述
以下是join方法源碼,這裏join()執行的是默認方法,傳入millis爲0。

  public final void join() throws InterruptedException {
        join(0);
    }

public final synchronized void join(long millis)
    throws InterruptedException {
        long base = System.currentTimeMillis();
        long now = 0;

        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (millis == 0) {
            while (isAlive()) {
                wait(0);
            }
        } else {
            while (isAlive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }

在這裏插入圖片描述
方式二:

使用java jdk5的一個方法:

   ExecutorService executorService = Executors.newSingleThreadExecutor();
   executorService.submit(thread1);
   executorService.submit(thread2);
   executorService.submit(thread3);
   executorService.shutdown();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章