作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试运行此 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/
我是一名优秀的程序员,十分优秀!