不用fash做的视频网站南京seo优化
三线程顺序打印1-100
题目
三个线程顺序打印1-100;
解题
基本思路
- 首先需要创建三个线程, 确定使用线程1打印
num % 3 = 1
的数, 线程2打印num % 3 = 2
的数, 线程3打印num % 3 = 0
的数; - 使用 synchronized 同步锁让每次只有一个线程进行打印, 每个线程打印前先判断当前数是否由当前线程打印, 若不由则让当前线程休眠;
- 打印需要的数后, 再唤醒其他的线程继续打印;
实现代码
public class ThreeThreadsPrint1_100 {// 当前打印数private int num = 1;// 锁private final Object lock = new Object();// flag 标记应该打印数对3取余的余数// 线程1 打印 num%3 = 1 的数// 线程2 打印 num%3 = 2 的数// 线程3 打印 num%3 = 0 的数public void printNum(int flag) {while (num <= 100) {synchronized (lock) {// 此处需要判断 num<=100// 确保不会有线程因为 101 % 3 != flag 而休眠 导致程序无法退出while (num % 3 != flag && num <= 100) {try {// 当前数 不由当前线程打印 让当前线程休眠lock.wait();} catch (InterruptedException e) {throw new RuntimeException(e);}}if (num <= 100) {// 打印System.out.println("当前线程: " + Thread.currentThread().getName() + "打印: " + num++);// 唤醒其他线程lock.notifyAll();}}}}public static void main(String[] args) throws InterruptedException {// 实例化对象ThreeThreadsPrint1_100 obj = new ThreeThreadsPrint1_100();Thread t1 = new Thread(() -> obj.printNum(1), "t1");Thread t2 = new Thread(() -> obj.printNum(2), "t2");Thread t3 = new Thread(() -> obj.printNum(0), "t3");// 不按顺序启动 验证是否成功实现t2.start();t1.start();t3.start();// 让主线程等到三个线程执行结束后再执行t1.join();t2.join();t3.join();}}