我必须显示显示 3 次的颜色类中的颜色,并且我需要使用线程添加 3 种不同颜色的实例,问题是我不知道如何开始,因为第三种颜色应该在任何时候开始显示第一个完成的:
public class Main {
public static void main(String[] args) throws InterruptedException {
Color color1 = new Color(“Blue”);
Color color2 = new Color(“Red”);
Color color3 = new Color(“White”);
}
}
class Color implements Runnable{
private String color ;
public Color(String color) {
this.color = color;
public void run(){
for (int i = 0; i < 3; i++) {
System.out.println(color);
try {
Thread.sleep(300);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
}
结果我需要的必须在控制台中打印3次蓝色3次红色3次白色,但是当蓝色或红色完成工作时,必须开始打印白色的线程。前两个线程应立即启动,但第三个线程仅应在前两个线程完成其工作后启动。
我正在考虑使用
BlockingQueue
队列,但我不确定这是否是一个好主意。
CountDownLatch
来实现此目的。从主线程调用 await()
并在其他线程中调用 countDown()
。这是一个例子:
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
Thread thread1 = new Thread(() -> {
System.out.println("Thraed 1 started");
foo();
latch.countDown();
System.out.println("Thraed 1 complete");
});
Thread thread2 = new Thread(() -> {
System.out.println("Thraed 2 started");
bar();
latch.countDown();
System.out.println("Thraed 2 complete");
});
thread1.start();
thread2.start();
System.out.println("Pausing main thread");
latch.await(); // Blocks until one of the threads calls latch.countDown()
System.out.println("Continuing main thread");
}
public static void foo() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void bar() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
输出为:
Pausing main thread
Thread 2 started
Thread 1 started
Thread 1 complete
Continuing main thread
Thread 2 complete