[英]Running fixed number of thread in parallel in java
我的應用程序中有3 threads
,但我只能並行運行 2 個線程。 一旦 1 個胎面停止,第三個線程將開始。
我知道Java
Thread
、 runnable
start()
、 run()
等,但我不知道如何實現上述情況。 你的小指導會很有幫助
嘗試使用信號量;
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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.