功能需求:
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 的顺序: