我不确定我是否完全理解了这个问题,但这似乎是我们想要按顺序打印线程的情况。一个示例是使用线程按如下顺序打印值:
线程 - 0 输出:1
线程 - 1 个输出:2
线程 - 2 输出:3
线程 - 0 输出:4
线程 - 1 个输出:5
线程 - 2 输出:6 等等..
如果这是要求,则可以编写用于 n 个线程的通用解决方案,其中每个线程将等待轮到它(使用它将尝试获取锁定的公共对象)。
class ResourceLock {
private volatile int currentThreadId;
private final int totalThreads;
public ResourceLock(int threadsCount) {
this.currentThreadId = 0;
this.totalThreads = threadsCount;
}
public void assignTokenToNextThread(int currentThreadNum) {
this.currentThreadId = (currentThreadNum + 1) % totalThreads;
}
public int getCurrentThreadId() {
return currentThreadId;
}
}
现在工作线程将完成其工作并使用上述类的实例进行锁定:
class Worker extends Thread {
private final ResourceLock resourceLock;
private final int threadId; // id of this thread
private final AtomicInteger counter; // counter shared by all threads, will print number in sequence.
private volatile boolean running = true; // flag to stop this thread when necessary
public Worker(ResourceLock resourceLock, int threadNumber, AtomicInteger counter) {
this.resourceLock = resourceLock;
this.threadId = threadNumber;
this.counter = counter;
}
@Override
public void run() {
while (running) {
try {
synchronized (resourceLock) {
while (resourceLock.getCurrentThreadId() != this.threadId) {
resourceLock.wait();
}
System.out.println("Thread:" + threadId + " value: " + counter.incrementAndGet());
Thread.sleep(1000);
resourceLock.assignTokenToNextThread(this.threadId);
resourceLock.notifyAll();
}
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
public void shutdown() {
running = false;
}
}
这可以测试为:
public static void main(String[] args) throws InterruptedException {
final int threadsCount = 3;
final ResourceLock lock = new ResourceLock(threadsCount);
Worker[] threads = new Worker[threadsCount];
final AtomicInteger counter = new AtomicInteger(0);
for(int i=0; i<threadsCount; i++) {
threads[i] = new Worker(lock, i, counter);
threads[i].start();
}
Thread.sleep(20000);
System.out.println("Will try to shutdown now...");
for(Worker worker: threads) {
worker.shutdown();
}
}