zoukankan      html  css  js  c++  java
  • 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  的顺序:

  • 相关阅读:
    转:详解iPhone Tableview分批显示数据 点击加载更多
    能不写全局变量就不写全局变量。
    ios 打电话 一键拨号
    下一步目标:整理出1套相对成熟的ios 开发框架
    dispatch_sync 线程 GCD iOS
    iOS 播放声音 最简单的方法
    判断 网络是否通常,以及判断用户使用的网络类型,时2G\3G\还是wifi
    ios 特效 新思路 :加载gif 动画,然后在动画上增加点击事件即可。
    Oracle小技巧
    excel导出时”内存或磁盘空间不足“错误的解决方法
  • 原文地址:https://www.cnblogs.com/android-deli/p/10231634.html
Copyright © 2011-2022 走看看