gpt4 book ai didi

java - JAVA中使用信号量控制线程访问

转载 作者:行者123 更新时间:2023-12-01 14:59:13 24 4
gpt4 key购买 nike

我正在尝试运行此 java 代码,但它无法正常工作。

请让我知道我做错了什么。

for 循环的 i 小于 10;。如果 i 小于 1(意味着没有循环),则程序可以正常工作,但对于 (i 小于 n),其中 n 大于 1,它会抛出异常

public class Main {

public static void main(String[] args) {
final Semaphore sem = new Semaphore(1, true);
Thread t1 = new Thread("TA") {
public void run() {
try {
sem.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("A");
sem.release();
}
};
Thread t2 = new Thread("TB") {
public void run() {
try {
sem.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("B");
sem.release();
}
};
Thread t3 = new Thread("TC") {
public void run() {
try {
sem.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("C");
sem.release();
}
};

for (int i = 0; i < 10; i++) {
t1.start();
t3.start();
t2.start();
}

}
}

最佳答案

您不能多次启动一个线程。因此,在第二次循环期间,第二次调用 t1.start() 时会出现异常。 javadoc 中对此进行了说明。 :

It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

Throws: IllegalThreadStateException - if the thread was already started.

您可以使用 ExecutorService 而不是直接操作线程。它可能看起来像这样:

public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(3);
final Semaphore sem = new Semaphore(1, true);
Runnable r1 = new Runnable() {
public void run() {
try {
sem.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("A");
sem.release();
}
};
Runnable r2 = new Runnable() {
public void run() {
try {
sem.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("B");
sem.release();
}
};
Runnable r3 = new Runnable() {
public void run() {
try {
sem.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("C");
sem.release();
}
};

for (int i = 0; i < 10; i++) {
executor.submit(r1);
executor.submit(r2);
executor.submit(r3);
}

executor.shutdown();
}

关于java - JAVA中使用信号量控制线程访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13923980/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com