Android-Java控制多線程執行順序


功能需求:

    Thread-0線程:打印 1 2 3 4 5 6

    Thread-1線程:打印1 1 2 3 4 5 6 

 

先看一個為實現(功能需求的案例)

package android.java;

// 定義打印任務(此對象只是打印任務,不是線程)
class PrintRunnable implements Runnable {

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

public class TestControlThread {

    public static void main(String[] args) {

        // 實例化 打印任務Runnable
        Runnable printRunnable = new PrintRunnable();

        // 創建第一個線程
        Thread thread1 = new Thread(printRunnable); // 把打印任務Runnable 給 線程執行

        // 創建第二個線程
        Thread thread2 = new Thread(printRunnable); // 把打印任務Runnable 給 線程執行

        // 啟動第一個線程
        thread1.start();

        // 啟動第二個線程
        thread2.start();
    }

}

 

執行結果:打印的結果每次都可能會不一樣,是由CPU隨機性決定的;

 

 


 

 

控制多線程執行順序

package android.java;

// 定義打印任務(此對象只是打印任務,不是線程)
class PrintRunnable implements Runnable {

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

public class TestControlThread {

    public static void main(String[] args) throws InterruptedException { // 注意⚠️:main不是重寫的方法,所以可以往外拋

        // 實例化 打印任務Runnable
        Runnable printRunnable = new PrintRunnable();

        // 創建第一個線程
        Thread thread1 = new Thread(printRunnable); // 把打印任務Runnable 給 線程執行

        // 創建第二個線程
        Thread thread2 = new Thread(printRunnable); // 把打印任務Runnable 給 線程執行

        // 啟動第一個線程
        thread1.start();

        /**
         * 取消主線程CPU執行資格/CPU執行權,60毫秒
         * 60毫秒后主線程恢復CPU執行資格/CPU執行權 --->>> 在去啟動第二個線程時:第一個線程已經執行完畢了,這樣就控制線程的順序了
         */
        Thread.sleep(60);

        // 啟動第二個線程
        thread2.start();
    }

}

 

執行結果:

 

現在CPU執行 Thread-0  Thread-1  的順序:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM