Shruti sharma
Shruti sharma

Reputation: 211

Running fixed number of thread in parallel in java

I have 3 threads in my application, but I am allowed to run only 2 threads in parallel. once 1 either of the tread will stop, 3rd thread will start.

I know Thread, runnable start(), run() etc in Java, But I dont know how to implement above situation. your little guidance will be very helpful

Upvotes: 0

Views: 181

Answers (2)

lonewolf
lonewolf

Reputation: 21

Use org.apache.tomcat.util.threads.ThreadPoolExecutor (provided by default in spring)

You can do something like this

List<Task> tasks = // create instances of classes which implement java.concurrent.Callable interface, in the call() method, add the business logic
ThreadPoolExecutor executor = new ThreadPoolExecutor(....)  // in the constructor add the parameters as per your requirement
executor.invokeAll(tasks);

This should execute your tasks with the maximum thread pool count as per your requirement.

If you're using spring consider defining a Configuration file that does the bean initialization for you, then Autowire the class where needed.

For more information on ThreadPools checkout this: https://www.baeldung.com/thread-pool-java-and-guava

Upvotes: 0

ZIHAO LIU
ZIHAO LIU

Reputation: 387

Try using semaphore;

public class Main {

    private static final Semaphore SEMAPHORE = new Semaphore(2);

    public static void main(String[] args) {
        runThread(new Thread(() -> runInThread(1)));
        runThread(new Thread(() -> runInThread(2)));
        runThread(new Thread(() -> runInThread(3)));

    }

    public static void runThread(Thread thread) {
        try {
            SEMAPHORE.acquire();
            thread.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void runInThread(int i) {
        System.out.println("Thread " + i + " is running");
        System.out.println("Thread " + i + " is waiting");
        try {
            Thread.sleep(i * 2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Thread " + i + " is finish");
        SEMAPHORE.release();
    }
}

Upvotes: 2

Related Questions