下面是一个示例代码,使用Java的同步计数器(CountDownLatch)来实现不同线程打印相同值的功能:
import java.util.concurrent.CountDownLatch;
public class PrintSameValue {
private static final int THREAD_COUNT = 3;
private static final int PRINT_TIMES = 5;
private static final CountDownLatch latch = new CountDownLatch(THREAD_COUNT);
public static void main(String[] args) {
for (int i = 0; i < THREAD_COUNT; i++) {
new Thread(new PrintThread(i)).start();
}
try {
latch.await(); // 等待所有线程准备就绪
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("All threads are ready!");
for (int i = 0; i < PRINT_TIMES; i++) {
System.out.println("Print value: " + i);
latch.countDown(); // 释放一个计数器
}
}
static class PrintThread implements Runnable {
private final int threadId;
public PrintThread(int threadId) {
this.threadId = threadId;
}
@Override
public void run() {
System.out.println("Thread " + threadId + " is ready!");
latch.countDown(); // 释放一个计数器
try {
latch.await(); // 等待主线程的信号
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < PRINT_TIMES; i++) {
System.out.println("Thread " + threadId + ": " + i);
latch.countDown(); // 释放一个计数器
}
}
}
}
以上代码创建了3个线程,并使用CountDownLatch来确保所有线程准备就绪后再开始打印。主线程等待所有线程准备就绪后,开始打印指定次数的值。每个线程打印指定次数的值后,再次释放一个计数器,直到所有线程的计数器都被释放完毕。