基本上我的代码如下所示:
private void runFreeThreads() {
ArrayList<ClassExtendsThread> tmpThreads = new ArrayList<ClassExtendsThread>(freeThreads);
freeThreads.clear();
System.out.println("Before the loop");
for (ClassExtendsThread thread : tmpThreads) {
thread.start();
}
System.out.println("After the loop");
}
问题是我使用this
初始化这些主题,而this
有一个名为threadReport()
的方法,看起来像
public void threadReport(boolean check, ClassExtendsThread someThread) {
freeThreads.add(someThread);
if (!check) {
return;
}
System.out.println("Trying to acquire semaphore");
try {
reportSem.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
runFreeThreads();
}
System.out.println("Semaphore is released!");
reportSem.release();
}
我在这里使用信号量就像一个互斥体,它基本上用1初始化。无论如何,我认为Thread.start()
实际上会调用run()
然后从父线程调度自己,但事实并非如此。
run方法是:
public class ClassExtendsThread extends Thread {
private ThreadController tControl;
private int threadNo;
public ClassExtendsThread (int threadNo, ThreadController threadController) {
tControl = threadController;
this.threadNo = threadNo;
}
public void run() {
System.out.println("Thread no: " + this.threadNo + " is running");
tControl.tReport(true, this);
}
}
所以我期待这样的结果(我也在run()
方法打印一些东西):
Trying to acquire semaphore
Before the loop
Thread no: 1 is running
Thread no: 2 is running
After the loop
Semaphore is released!
...
但实际上发生的事情是:
Trying to acquire semaphore
Before the loop
Thread no: 1 is running
Thread no: 2 is running
Trying to acquire semaphore
Trying to acquire semaphore
然后它挂起。因为它永远不会退出循环。有没有快速解决方法?