在Java中,Thread.start()不从父线程分派

在Java中,Thread.start()不从父线程分派,java,multithreading,semaphore,Java,Multithreading,Semaphore,基本上,我的代码如下所示: private void runFreeThreads() { ArrayList<ClassExtendsThread> tmpThreads = new ArrayList<ClassExtendsThread>(freeThreads); freeThreads.clear(); System.out.println("Before the loop"); for (ClassExtendsThread t

基本上,我的代码如下所示:

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");
}
我在这里像互斥一样使用信号量,它基本上是用1初始化的。无论如何,我认为
Thread.start()
实际上会调用
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()
method中打印一些内容):

然而,实际上发生的情况是:

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

然后它就挂了。因为它从不退出循环。有没有一种快速的方法可以解决这个问题?

运行方法的代码也是必需的。我更担心的是您试图解决的实际用例是什么。您的代码看起来很复杂,很容易出现错误。你想用这些线程实现什么?@Kayaman,基本上我想让线程处理一项任务。一旦完成了任务,然后<代码> Run()>代码>调用一个方法:“代码> thReRePoT())/<代码>,它保持线程不工作的轨迹并分配给它们任务。看看实用程序类的java.util.concurrent包:是的,正如Puce所说,您正在尝试实现一些已经创建的东西,主要是
Executor
框架。不要自己写,而是使用经过测试的版本。
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