Java Mulithreading: All of my threads get the same thread id

Viewed 599

I'm required to use multithreading for a project in my programming class so to practice and see how it works I used the code which was presented in the class. However, when I run the code all threads have the same ID, is this because of my system or does it has another reason?

This is the code:

MyThread.java:

public class MyThread implements Runnable {
    public void run() {
        try{
            System.out.println("Thread id: " + Thread.currentThread().getId());
            for(int i = 0; i <= 10; i++){
                System.out.println(i);
            }
        }
        catch (Exception e){
            System.out.println(e.getCause().toString());
            return;
        }
    }
}

App.java:

public class App {
    public static void main(String[] args) {
        MyThread [] threads = new MyThread[3];

        for(int i = 0; i < 3; i++){
            threads[i] = new MyThread();
        }
        for(int i = 0; i < 3; i++){
            threads[i].run();
        }
    }
}
1 Answers

Your program doesn't create any threads. The reason why your run() method prints the same ID four times is because you call it from the same thread—the "main" thread—four times. The only way a new thread can ever be created in Java is if some code (either your own code, or code in a library that is invoked by your code) calls the start() method of a Thread instance.

You didn't show the complete declaration of the class that contains the run() method. I'm going to pretend that it looks like this:

class MyThread implements Runnable {
    public void run() {
        ...
    }
}

The simplest way* to have that run() method called by a new thread is to create a MyThread instance, and make it the delegate of a java.lang.Thread instance:

MyThread my_thread = new MyThread();
Thread t = new Thread(my_thread);
t.start();

The t.start() call is what creates the actual operating system thread.


Note: Since MyThread instances are not actually threads, a better name might be MyRunnable or any name that does not contain "thread."


* Creating a new thread is a serious undertaking. If you were writing code for a large-scale software project, your co-workers probably would discourage you from directly instantiating and start()ing new Thread objects. They probably would ask you instead to either use a thread pool or a thread factory that was provided to your code by some other part of the system.

That trick, which potentially would give them better ability to observe and/or manage the system's threads, is another example of delegation. Delegation is a powerful technique used in object-oriented programming that is well worth learning.

Related