一个线程总是在没有其他线程的情况下运行

时间:2011-01-26 18:31:52

标签: java multithreading

为什么主线程永远不会被执行?我认为这是我使用Thread.sleep(int value)我给其他线程运行的机会,但这绝不会发生。

    public static void main(String[] args) {
        final Sook o = new Sook();
        Thread t = new Thread(new Runnable() {
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(10000); // Specially set to give a chance to the main thread to run
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        t.run();

        System.out.println("<<<<<BACK TO MAIN >>>>>>"); // Never happens
    }

1 个答案:

答案 0 :(得分:12)

请勿调用t.run(),调用t.start()

只需运行将调用当前线程中的run方法。