问题描述
给指定线程数threadSum,将数字从初始值开始连续打印n个数字(数字步长为1)
解题思路
考察多线程使用,由于是指定线程数,我们需要动态创建线程,threadSum个线程要执行同一个逻辑,因此需要在此逻辑中设计个线程执行逻辑即可。执行打印的线程是固定的,JDK中已有的线程同步工具中,Semaphore是比较符合这种场景的,通过加减令牌让线程之间协同按序打印。
实现逻辑
public static void main(String[] args) throws InterruptedException {
print(2, 2, 7);
}
public static void print(int threadSum, final int initialValue, final int n) {
// 从initialValue开始打印
AtomicInteger index = new AtomicInteger(initialValue);
Semaphore[] semaphores = new Semaphore[threadSum];
for (int i = 0; i < threadSum; i++) {
if (i == threadSum - 1) {
// 新增一个令牌
semaphores[i] = new Semaphore(1);
} else {
semaphores[i] = new Semaphore(0);
}
}
AtomicInteger i = new AtomicInteger(0);
for (; i.get() < threadSum; i.getAndIncrement()) {
final Semaphore firstSemaphore = i.get() == 0 ? semaphores[threadSum - 1] : semaphores[i.get() - 1];
final Semaphore currentSemaphore = semaphores[i.get()];
new Thread(() -> {
boolean finished = false;
while (!finished) {
// 扣除当前线程对应令牌,如有令牌继续执行,否则阻塞
try {
firstSemaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":" + index.getAndIncrement());
if (index.get() - initialValue >= n) {
finished = true;
}
currentSemaphore.release();
}
}).start();
}
}
打印结果
Thread-0:1
Thread-1:2
Thread-2:3
Thread-3:4
Thread-4:5
Thread-0:6
Thread-1:7
Thread-2:8
Thread-3:9
Thread-4:10
Thread-0:11