Home » Java » Java Multithreading one after another until loop end-Exceptionshub

Java Multithreading one after another until loop end-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have two threads (ThreadA and ThreadB) in Thread pool. I call run method using runnable interface. In runnable there is for loop, I have to execute this one after another.
example: first ThreadA executes, next ThreadB, next ThreadA, next ThreadB, … like this until completion of the loop.

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

public class OneAfterAnother implements Runnable {
    public static void main(String[] args) {
        ExecutorService executorService = null;
        try {
            executorService = Executors.newFixedThreadPool(2);
            OneAfterAnother oneAfterAnother = new OneAfterAnother();
            for (int i = 0; i < 2; i++) {
                executorService.execute(oneAfterAnother);
            }
        } finally {
            executorService.shutdown();
        }
    }

    @Override
    public void run() {
        for (int i = 1; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + "===" + i);
        }
    }
}
How to&Answers: