在java中并行运行固定数量的线程

我的应用程序中有 3 threads,但我只能并行运行 2 个线程。 一旦 1 个胎面停止,第 3 个线程将开始。

我知道 Thread 中的 runnablestart() run()Java 等,但我不知道如何实现上述情况。你的小指导会很有帮助

jjjjj662002 回答:在java中并行运行固定数量的线程

尝试使用信号量;

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();
    }
}

本文链接:https://www.f2er.com/48538.html

大家都在问