Java Concurrency 01----Two Ways to Create Threads in Traditional Threads



  There are two ways to create threads in the traditional threading technology: one is to inherit the Threadclass and override the run()method ; the other is to implement Runnablethe interface, overwrite the run()methods in the Runnableinterface, and throw the implementation ofThread the interface . Most people probably know these two ways, but why is it OK to play this way? Let us analyze the ins and outs of these two methods in detail.

1. Demystifying run() in Thread

  We saw above that these two methods are related run()to methods, so let's take a look at what the methods Threadin the source code run()do:

@Override
public void run() {
    if (target != null) {
        target.run();
    }
}
  
  

      We can see that the run()method is very simple. There is only one ifstatement. If the target is not empty, the run()method of the target will be executed, otherwise it will not do anything. So what is the sacredness of the target? We click in to see:

    private Runnable target;
      
      

        The original target is the Runnable interface, let's click on Runnable to see:

      @FunctionalInterface
      public interface Runnable {
          public abstract void run();
      }
        
        

          There is only one method in Runnable, and it is also a run()method! Well, now go back to the run()method of the Thread class, if the target is not empty, that is, the Runnable interface is implemented, that is, the run()methods in Runnable are implemented, then we use the run()methods in the interface; if the target is empty, that is If the Runnable interface is not implemented, then we do nothing, that is, the thread disappears immediately after it is created.
          So here, everyone understands why there are two ways to create threads. The first: Don't you have to ifjudge first? I don't judge now, I will ifkill you, I run()will write the code in the method, I can do whatever I want, that is, rewrite the run()method in Thread, the second: don't you want to ifjudge first? Okay, I will give you a Runnable interface for you to judge, but you still have to call the run()methods in my Runnable, then I can just rewrite the run()methods in my Runnable!  
          After knowing the ins and outs, let's write an example for these two traditional methods.

        2. Creation method 1: Inherit the Thread class

          Create and start a thread in two steps:

        • Inherit the Threadclass and implement the run()method;
        • Call start()the method to start the thread.

        Since we only need to implement one run()method, we can use anonymous inner classes in java to implement it, as follows:

        public class TraditionalThread {
        
            public static void main(String[] args) {
        
                /********** 第一种方法:继承Thread类,覆写run()方法 **************/
                Thread thread1 = new Thread(){
        
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(500);//让线程休息500毫秒
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName());//打印出当前线程名
                    }
                };
                thread1.start();//开启线程
            }
        }
          
          

          3. Creation method 2: Implement the Runnable interface

            Create and start a thread in two steps:

          • Implement the Runnableinterface, and implement the run()method;
          • Call start()the method to start the thread.

          Since we only need to implement one run()method, we can also use anonymous inner classes in java to implement it, as follows:

          public class TraditionalThread {
          
              public static void main(String[] args) {
          
                  /********** 第二种方法:实现Runnable接口,扔给Thread **************/
                  Thread thread2 = new Thread(new Runnable() {
          
                      @Override
                      public void run() {
                          try {
                              Thread.sleep(500);
                          } catch (InterruptedException e) {
                              e.printStackTrace();
                          }
                          System.out.println(Thread.currentThread().getName());
          
                      }
                  });
                  thread2.start();
              }
          }
            
            

            4. Use both methods at the same time

              If there is a buddy who is more powerful, he uses two methods at the same time, namely: not only implements the run()method in the Thread class, but also throws a run()Runnable that implements the method to Thread. As follows:

            public class TraditionalThread {
            
                public static void main(String[] args) {
                    //这哥们的代码写的比较给力
                    new Thread(new Runnable() {
            
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            System.out.println("Runnable:" + Thread.currentThread().getName());
                        }
                    }){
            
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            System.out.println("Thread:" + Thread.currentThread().getName());
                        }
            
                    }.start();
                }
            
            }
              
              

                Which will be executed now? When we run the above program, we will find that it will print out the information of Thread, so it is running the run()method of Thread, and we know the conclusion, but why?
                Consider from object-oriented thinking: the above code is actually a new object (child object) that inherits the Thread object (parent object), rewrites the run()method of the parent class in the child object, and throws a Runnable in the parent object In, the method in the parent object run()is the initial method with ifjudgment run().
                Well, start()after executing it now, you must first find a method in the subclass. If you find run()it, the method of the parent class will be killed, so Thread: will be printed. If we now assume that there is no overridden method in the run()subclass , then it must be run()To go to the parent class to find a run()method, the parent class run()method has to judge whether there is a Runnable passed in, and now there is one, so execute the run()method in Runnable, then it will print Runnable: out.
                   
               




                There are two ways to create threads in the traditional threading technology: one is to inherit the Threadclass and override the run()method ; the other is to implement Runnablethe interface, overwrite the run()methods in the Runnableinterface, and throw the implementation ofThread the interface . Most people probably know these two ways, but why is it OK to play this way? Let us analyze the ins and outs of these two methods in detail.

              Guess you like

              Origin http://10.200.1.11:23101/article/api/json?id=326946022&siteId=291194637