用Java写上面这个问题
时间: 2024-11-03 12:12:54 浏览: 8
java web手写实现分页功能
在Java中,我们可以使用`java.util.concurrent`包下的`ExecutorService`和`Future`来创建线程池,并结合`CountDownLatch`来控制线程的执行顺序,以便线程A和线程B交替输出。以下是使用Java实现的版本:
```java
import java.util.concurrent.*;
public class ThreadDemo {
private static final int COUNT_DOWN = 1000;
public static void main(String[] args) throws InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(2);
CountDownLatch startLatch = new CountDownLatch(2);
Future<?> futureA = executor.submit(new OutputThread("A", startLatch, COUNT_DOWN));
Future<?> futureB = executor.submit(new OutputThread("B", startLatch, COUNT_DOWN));
startLatch.await(); // 等待两个任务都启动
executor.shutdown(); // 关闭线程池
futureA.get(); // 阻塞等待A完成
futureB.get(); // 阻塞等待B完成
}
static class OutputThread implements Runnable {
private final String name;
private final CountDownLatch startLatch;
private final int countDown;
public OutputThread(String name, CountDownLatch startLatch, int countDown) {
this.name = name;
this.startLatch = startLatch;
this.countDown = countDown;
}
@Override
public void run() {
try {
startLatch.countDown(); // 启动信号,允许另一个线程开始
while (countDown > 0) {
System.out.printf("[%s] %d,%n", name, --countDown);
Thread.sleep(200); // 模拟0.2秒间隔
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
阅读全文