0
votes

I am having difficulty understanding the behavior of inner class threads.

I have this simple test program.

public class Test {
    private static Random rand = new Random(System.currentTimeMillis());

    public class TestThread extends Thread {
        @Override
        public void start() {
            System.out.println("in start " + Thread.currentThread().getName());
            try {
                Thread.sleep(rand.nextInt(5000));
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args){
        System.out.println(Thread.currentThread().getName());
        for(int i = 0; i < 5; ++i){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(rand.nextInt(5000));
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName());
                }
            }).start();
        }

        System.out.println("new run");
        Test test = new Test();
        for(int i = 0; i < 5; ++i){
            (test. new TestThread()).start();
        }
    }
}

When the first for loop runs, the threads behaves as I expected. Total of 6 threads, main, thread-0, thread-1, thread-2, thread-3, and thread-4. Thread 0 - 4 are printed out of order as I expected.

The result for second for loop has me confused.

system.out.println("in start " + Thread.currentThread().getName());

It always prints out "main," and the threads are executed sequentially. Why is the execution of the inner class thread carried out by the main thread?

Thanks!

2

2 Answers

4
votes

Don't override Thread.start(). The start method is always called from the thread that is starting it. You need to override Thread.run().

(See examples in the Thread class' javadoc documentation)

0
votes

You shouldn't @Override the start() method. You should @Override run() instead. Then call start().