Why we call Thread.start() method which in turns calls run method?

后端 未结 12 1120
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-29 01:40

Why do we call the thread object\'s start() method which in turns calls run() method, why not we directly call run() method?

12条回答
  •  执笔经年
    2020-11-29 02:41

    When we use start method then a new thread is created and then code inside the run method will be executed for each new Thread.

    Use of start method creates two stack for each thread ,Stack and native stack.

    But Run method call just execute the code inside the run method sequentially as run method call does not create different stacks.

    Example

    import java.util.concurrent.TimeUnit;
    
    public class thread implements Runnable{
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            Thread gg=new Thread(new thread());
            Thread gg1=new Thread(new thread());
            gg.run();
            gg1.start();
            /*gg.start();
            gg1.start();*/
    
        }
    
        @Override
        public void run() {
            for(int i=0;i<5;i++)
            {
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            System.out.println("Hello..." + i);
            }
    
        }
    
    }
    

提交回复
热议问题