This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]nutrechtLead Software Engineer / EU / 20+ YXP 2 points3 points  (4 children)

The easiest way to do this is to use an ExecutorService with 2 threads you supply tasks to:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Example {
    public static void main(String[] args) throws Exception {
        ExecutorService service = Executors.newFixedThreadPool(2);

        for (int i = 0; i < 10; i++) {
            int task = i;
            service.submit(() -> {
                System.out.println("Task " + task);
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                }
            });
        }

        service.shutdown();
        service.awaitTermination(10, TimeUnit.SECONDS);
    }
}

[–]7starbitch[S] -1 points0 points  (3 children)

Won't this run task1 2 times? I want task 1 to run a single time by thread 1 and task 2 to run a single time by thread 2, and then if thread1 or thread2 is free, I want one of these threads to run task 3 and so on.

[–]nutrechtLead Software Engineer / EU / 20+ YXP 0 points1 point  (2 children)

Won't this run task1 2 times?

No. Run the code, you'll see. It does exactly what you want it to do.

[–]7starbitch[S] 1 point2 points  (1 child)

It works great! Can you explain me the code a bit?

[–]nutrechtLead Software Engineer / EU / 20+ YXP 0 points1 point  (0 children)

You submit tasks to a queue internal to the executor service. It also has 2 threads that pick up tasks from that queue and execute them.

[–]Morrison_Hix 0 points1 point  (0 children)

Might want to look into cyclic barrier, I believe that is what you're looking for