package com.hnist.lzn.Java8;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import java.util.*;
/**
* N个线程轮流打印数字问题
*/
public class Test implements Runnable{
/*
要求3个线程,按顺序打印1,2,3,。。。75.
线程1先打印1,2,3,4,5,线程2再打印6,7,8,9,10,线程3,打印11,12,13,14,15.
依次类推
*/
int id;
volatile static int num = 1;
public Test(int id){
this.id = id;
}
//这个类就是封装3个线程统一的任务,在run方法中
//怎么区分三个线程,就要一个标志,怎么做?
//怎么保证三个线程依次顺序操作?
@Override
public void run() {
//多线程外部加while,保证多线程竞争时条件机制的保证
//每个线程打印需要一个变量,于是引入num(很自然的引入)
// 使用了wait(),notifyAll(),必须在锁机制下
synchronized (Test.class) {
while (num <= 75) {
//num/5%3==id满足当前线程id就打印
//其次就应该唤醒下一个线程
// true 应该是唤醒机制
// false 是阻塞
if (num / 5 % 3 == id) {
System.out.println("ud" + id + ":");
for (int i = 0; i < 5; i++) {
System.out.print(num++ + ",");
}
System.out.println();
//唤醒下一个线程
Test.class.notifyAll();
} else {
//不满足,阻塞
try {
Test.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
new Thread(new Test(0)).start();
new Thread(new Test(1)).start();
new Thread(new Test(2)).start();
}
}
总结:1.单独的类实现Runnable接口,重写run方法,达成统一逻辑,同时,static num变量。
2.3个线程,轮流打印75,每个线程轮流打印5下,for 循环即可。
3.主要是利用 线程间,等待唤醒机制 wait(),notifyAll(),必须是在竞争锁的情况下。synchronized
4.巧妙的利用if (num / 5 % 3 == id) 来控制线程唤醒等待代码。
5.扩散到 N个线程打印N个数。