实现思路:要顺序打印数字,首先要保证打印处于同步的语句块中,这个可以用synchronized实现;其次,可以采用线程顺序来保证数字顺序,在for循环中开启线程,可以保证线程是有序的。
package com.xicheng.bigdata;
/**
* @author liubin52
* @date 2018/11/6
* @description
*/
public class PrintSequenceTest implements Runnable{
private static final Object LOCK = new Object();
// 当前数字
private static int currentNo = 0;
// 线程编号
private int threadNo;
// 线程总数
private int threadCnt;
// 数字总数
private int max;
public PrintSequenceTest() {
}
public PrintSequenceTest(int max, int threadNo, int threadCnt) {
this.max = max;
this.threadCnt = threadCnt;
this.threadNo = threadNo;
}
@Override
public void run() {
while (true) {
synchronized (LOCK) {
while (currentNo % threadCnt != threadNo) {
if (currentNo > max) {
break;
}
try {
LOCK.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (currentNo > max) {
break;
}
System.out.println("Thread-" + threadNo + ":" + currentNo);
currentNo++;
LOCK.notifyAll();
}
}
}
public static void main(String[] args) {
int threadCnt = 3;
int max = 10;
for(int i = 0; i < threadCnt; i++) {
new Thread(new PrintSequenceTest(max, i, threadCnt)).start();
}
}
}