Below code works successfully, so we can run the thread twice?

Below code works well, so does that mean we can run the 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 - number of revolutions 0 number of starts 1

+3


source to share


2 answers


No, you only started a new thread once when you called obj.start()

. obj.run()

executes the method run

on the current thread. It does not 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.

+7


source


The life cycle of a Thread ends at Thread.State.TERMINATED.

All you did was run the method run()

from the same thread - main

-Thread.

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

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();
}}

      



Executing this result:

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

      

Hope this clarifies!

0


source







All Articles