思路是自己实现一个 Thread,名为 MyThread,成员变量有 id,这是每一个线程都有的 id,静态变量 now 是当前该哪个线程打印数字了,也是一个 ID。
并且使用 AtomicInteger 保证数字的并发安全,只需要将每一个线程的任务设置为如下所示:
while (atomicInteger.get() < M) {
if (now != id) {
continue;
} else {
System.out.println(id + " - " + atomicInteger.getAndIncrement());
now = (now + 1) % N;
}
}
当 now != id 时,证明现在轮不到此线程打印,那么让它空轮询。 由于每一个线程都需要知道 now 的最新值,所以要将其设置为 volatile
public class Main {
/**
* 最大线程数
*/
private static final int N = 10;
/**
* 打印的最大值
*/
private static final int M = 100;
static class MyThread extends Thread {
/**
* 当前线程的id,不变
*/
private int id;
/**
* 现在该哪个线程打印了,递增
*/
private static volatile int now;
private static final AtomicInteger NUM = new AtomicInteger(0);
public MyThread(int id) {
this.id = id;
this.setName("线程" + id);
}
@Override
public void run() {
while (NUM.get() < M) {
if (id != now) {
continue;
} else {
System.out.println(Thread.currentThread().getName() + " - " + NUM.getAndIncrement());
now = (now + 1) % N;
}
}
}
}
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < N; i++) {
MyThread myThread = new MyThread(i);
myThread.join();
myThread.start();
}
}
}