【问题标题】:Running fixed number of thread in parallel in java在java中并行运行固定数量的线程
【发布时间】:2021-07-23 10:34:24
【问题描述】:
我的应用程序中有3 threads,但我只能并行运行 2 个线程。
一旦 1 个线程停止,第 3 个线程将启动。
我知道Thread,runnablestart(),run()等Java,但我不知道如何实现上述情况。你的小指导会很有帮助
【问题讨论】:
标签:
java
spring
multithreading
spring-boot
java-8
【解决方案1】:
尝试使用信号量;
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();
}
}