簡體   English   中英

在java中並行運行固定數量的線程

[英]Running fixed number of thread in parallel in java

我的應用程序中有3 threads ,但我只能並行運行 2 個線程。 一旦 1 個胎面停止,第三個線程將開始。

我知道Java Threadrunnable 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM