1

This is the code for my thread test.

class TestThread extends Thread {   
    @Override
    public void run() {
        while (true) {
            System.out.println("Run thread "+this.getId());
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

In the main function, I set up 100 threads:

for (int i = 0; i < 100; i++) {
    TestThread tt = new TestThread();
    tt.run();
}

And this is the result I got

Run thread 8
Run thread 8
Run thread 8
Run thread 8
...

Why only thread 8 printed out? It seems that this is the only thread that is running. How can I make other threads work?

Hieu Nguyen
  • 382
  • 2
  • 15

3 Answers3

4

Thread.run will call the threads run-method directly. It will be executed synchronously, not parallel.

To run a thread asynchronously, use Thread.start().

By the way: Extending Thread and starting the thread-objects directly is not recommended. It is usually far better to implement your tasks as a Runnable and then use a ThreadPoolExecutor to implement multithreading.

Philipp
  • 67,764
  • 9
  • 118
  • 153
3

to start a thread. use start() method instead of run().

what you're doing now is basically running that function.

kucing_terbang
  • 4,991
  • 2
  • 22
  • 28
0

You should be calling thread. start instead of thread.run.