Why can't we call the start method twice on a same instance of the Thread object?

后端 未结 5 1444
孤街浪徒
孤街浪徒 2020-12-03 03:16

I was reading about threads and found that we can\'t call the start method twice on the same thread instance. But I didn\'t understand the exact reason for the same. So why

5条回答
  •  独厮守ぢ
    2020-12-03 03:45

    This is my opinion, It is due to Thread id. Thread scheduler is identifying the thread through the thread id. It is unique real number. Please find below code,

        public class StartTwice extends Thread {
    
        public void run() {
            System.out.println("running...");
        }
    
        public static void main(String[] args) {
    
            StartTwice start1 = new StartTwice();
            System.out.println("Thread id: " + start1.getId());
            start1.start();
    
            start1 = new StartTwice();
            System.out.println("Thread id: " + start1.getId());
            start1.start();
        }
    
    }
    
    Output is:
    
    Thread id: 10
    Thread id: 11
    running...
    running...
    

    When I re-instantiate the start1 object. A new thread id is created.

    PS: Even a thread is done, we can't use the same object (thread id) second time. Until or unless the JVM is reuse that id.

提交回复
热议问题