3

Below code runs successfully, so does it mean we can start thread twice?

public class enu extends Thread {
    static int count = 0;

    public void run(){
        System.out.println("running count "+count++);
    }

    public static void main(String[] args) {
        enu obj = new enu();
        obj.run();
        obj.start();
    }
}

output - running count 0 running count 1

hennes
  • 8,542
  • 3
  • 40
  • 59
Sumit Ganjave
  • 53
  • 1
  • 6

2 Answers2

7

No, you only started a new thread once, when you called obj.start(). obj.run() executes the run method in the current thread. It doesn't create a new thread, and you can call it as many times as you like.

On the other hand, calling obj.start() more than once is not possible.

Eran
  • 359,724
  • 45
  • 626
  • 694
  • [This thread](http://stackoverflow.com/questions/8579657/java-whats-the-difference-between-thread-start-and-runnable-run) has some more details on the differences. – Ray Hylock Apr 26 '15 at 08:21
  • When start() method is called on a thread, it itself calls the run() method automatically. – Pinky Apr 26 '15 at 09:17
0

The Thread lifecycle ends at Thread.State.TERMINATED.

All you did was running the run() method from the same thread - the main-Thread.

Theres a really simple test if you want to check the access of Threads in code parts:

public class randtom extends Thread {
static int count = 0;

public void run(){
    System.out.println(Thread.currentThread().toString());      
    System.out.println("running count "+count++);
}

public static void main(String[] args) {
    randtom obj = new randtom();
    obj.run();
    obj.start();
}}

Running this results in:

Thread[main,5,main]
running count 0
Thread[Thread-0,5,main]
running count 1

Hope this clarifies!

Liebertee
  • 88
  • 9