前言:
不同的线程执行的时候会去抢cpu的资源。你的cpu是几核就代表你的cpu可以同时执行多少个线程。另外人脑只有一核。不能够同时做两件事。能够边玩游戏,边敲代码是因为我们的频繁切换。比如说黑屏了,就敲敲代码,faker打比赛也只能通过切屏看队友在干嘛,不能一边跟对手火拼,一边监督队友。
我们现在需要循环打印01,可以一个线程套个for循环,然后懂得都懂,奇数打印1,偶数打印0。但是我们现在学习的是多线程,所以我们要以理解多线程的思想来进行写代码。
代码:
package com.dmdd.practice;
public class Five {
private static Thread thread2 = null;
public static Thread thread1 = null;
public static void main(String[] args) {
thread1 = new Thread(() -> {
while (true) {
try {
System.out.println("1");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
thread2.resume();
thread1.suspend();
}
}
});
thread2 = new Thread(() -> {
while (true) {
try {
System.out.println("0");
//
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
thread1.resume();
thread2.suspend();
}
}
});
thread2.start();
thread1.start();
}
}
通过线程的互相的挂起和禁用实现依次执行,让他们排好队,不用打的头破血流