I have to display colors from the color class which displays 3 times and I need to add instances of 3 different colors using threads, the problem is that I don't know how to start because the 3rd color is supposed to start displaying when any of the first ones finishes:
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();
}
}
}
}
}
Result what I need must print in console 3 times blue 3 times red 3 times white, but when either blue or red finishes working, the thread printing white must start. The first two threads should start immediately but the third one should only start once either of the first two threads complete their work.
I was thinking of using BlockingQueue
queues, but I am not sure if this is a good idea.
import java.util.concurrent.CountDownLatch;
public class Main {
public static void main(String[] args) throws InterruptedException {
// Create a CountDownLatch with a count of 1 to signal when a thread finishes
CountDownLatch latch = new CountDownLatch(1);
// Create tasks for each color
Task taskBlue = new Task(latch, "Blue", 300);
Task taskRed = new Task(latch, "Red", 300);
Task taskWhite = new Task(latch, "White", 300);
// Start the threads
taskBlue.start();
taskRed.start();
System.out.println("Waiting for Red or Blue to complete...");
latch.await();
System.out.println("Starting white");
taskWhite.start();
}
}
class Task implements Runnable {
private final String color;
private final CountDownLatch latch;
private final int delayInMs;
private Thread thread;
public Task(CountDownLatch latch, String color, int delayInMs) {
this.latch = latch;
this.color = color;
this.delayInMs = delayInMs;
}
public void start() {
this.thread = new Thread(this);
this.thread.start();
}
@Override
public void run() {
try {
for (int i = 0; i < 3; i++) {
System.out.println(" " + color);
Thread.sleep(this.delayInMs);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
latch.countDown(); // Decrement the latch count when the task finishes
}
}
}
Please note I decreased the delay of Red to demonstrate white is triggered as soon as one of the tasks (Blue or Red) completes.
Outputs:
Waiting for Red or Blue to complete...
Red
Blue
Red
Red
Blue
Starting white
White
Blue
White
White
Giving each task 300 ms delay:
Waiting for Red or Blue to complete...
Red
Blue
Red
Blue
Red
Blue
Starting white
White
White
White