网上看到了一个题目:
输入N个线程,然后顺序打印数字从0到100,输出结果类似如下:
thread0 value is0
thread1 value is1
thread2 value is2
thread3 value is3
thread0 value is4
思路是解决线程的序号,定义一个atomic的原子inter,初始值为0,然后判断序号是否等于inter的值,或者inter整除N是否等于
当前序号,如果等于,则打印,并将原子int 自增,并唤醒其他的线程,否则的话就等待。
只测试了部分值,发现没有问题。
代码如下:
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
//通过N个线程顺序循环打印从0至100
public class ThreadDemo implements Runnable {
private static int totalNumber = 100;
private static AtomicInteger value = new AtomicInteger(0);
private static int inputNum = 0;
private static CountDownLatch countDownLatch;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int threadNum = in.nextInt();
inputNum = threadNum;
countDownLatch = new CountDownLatch(threadNum);
for (int i = 0; i < threadNum; i++) {
new Thread(new ThreadDemo(), "thread" + i).start();
countDownLatch.countDown();
}
}
@Override
public void run() {
try {
countDownLatch.await();
//System.out.println("begin value is " + value.get());
while (value.get() < totalNumber) {
synchronized (value) {
String name = Thread.currentThread().getName();
int taskThreadNum = Integer.parseInt(name.substring(6, 7));
if (value.get() == taskThreadNum || value.get() % inputNum == taskThreadNum) {
System.out.println(name + " value is" + value);
value.getAndIncrement();
value.notifyAll();
} else {
value.wait();
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}