简体   繁体   English

无法启动线程(实现Runnable)

[英]Can't start a thread (implementing Runnable)

Could you help me understand why my FreeThread doesn't start a thread. 您能帮助我理解为什么我的FreeThread无法启动线程吗? Well, I can see that threads corresponding to HotThreads appear in the debagger. 好吧,我看到对应于HotThreads的线程出现在了debagger中。 But when I add a FreeThread, no thread appears. 但是,当我添加一个FreeThread时,没有线程出现。 If I try to trace it step by step, the cursor doesn't go to the superclass overridden run(), but goes to the start() method of Thread class. 如果我尝试逐步跟踪它,则光标不会转到覆盖超类的run(),而是转到Thread类的start()方法。

Anyway, any help how to start FreeThreads would be highly appreciated. 无论如何,将非常感谢您对启动FreeThreads的任何帮助。

public class HotThread implements Runnable{
    @Override
    public void run() {}
}

public class FreeThread extends HotThread {
   public FreeThread(int timeout) {
        super();
        ...  
    }
}

public class ThreadPool {
     public ThreadPool(int numberOfHotThreads) {
         for (int i = 0; i < numberOfHotThreads; i++) {
            HotThread ht;
            Thread t;
                ht = new HotThread(); // Нагруженный поток (есть задача).
                t = new Thread(ht);
                t.start();
         }
     }

    public void addFreeThread() {
        FreeThread ft = new FreeThread();
        Thread t = new Thread(ft);        
        t.start();
    }
} 
 public void run() {} 

So if your run() method really empty, then the thread is starting but immediately finishing and you never see them in the debugger because they've already completed. 因此,如果您的run()方法确实为空,则该线程正在启​​动但立即完成,并且您永远不会在调试器中看到它们,因为它们已经完成。 Try putting a Thread.sleep(10000000); 尝试放入Thread.sleep(10000000); so you can see the thread running. 这样您就可以看到线程正在运行。 Or as @Radiodef commented, you could put a breakpoint there in the debugger and it should stop there. 或者,正如@Radiodef所评论的那样,您可以在调试器中放置一个断点,并且该断点应该在那里停止。

No, not empty. 不,不是空的。 There is Thread.currentThread().start(); 有Thread.currentThread()。start(); there. 那里。

This is wrong. 错了 If you enter the run() method then the thread is already starting. 如果输入run()方法,则该线程已经启动。 By trying to start() it again, you will cause an IllegalThreadStateException to be thrown because of an incorrect thread state which will kill the running thread immediately. 通过再次尝试start() ,您将导致抛出IllegalThreadStateException ,因为线程状态不正确会立即杀死正在运行的线程。 The idea that you can ever start() the current (running) thread is an invalid concept by definition. 根据定义,您可以start()当前(正在运行)线程的想法是无效的概念。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM