• 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  的顺序:

  • 相关阅读:
    如何删除一个CSDN上自己上传的资源
    ubuntu 安装 boost
    C#-提取网页中的超链接
    数组地址详解
    约瑟夫环-源码
    树的基础概念(二)
    二叉树的主要操作
    二叉树的简介及链式结构实现
    树的基础概念
    栈实现数的进制转换
  • 原文地址:https://www.cnblogs.com/android-deli/p/10231634.html
Copyright © 2020-2023  润新知