Multithreading thread / runnable

1. Option One: inheritance thread.

 1 package com.example.demo;
 2 
 3 
 4  
 5 //1. 方法1,继承thread类:Thread implements Runnable
 6 package com.example.demo;
 7 public class ThreadCreateDemo1 {
 8     public static void main(String[] args) {
 9         MyThread thread = new MyThread();
10         MyThread thread1 = new MyThread();
11         MyThread thread2 = new MyThread();
12         thread.start(); //This method is called multiple times, occurs an IllegalThreadStateException 
13 is          thread1.start (); // This method is called multiple times, occurs an IllegalThreadStateException 
14          thread2.start (); // This method is called multiple times, occurs an IllegalThreadStateException 
15      }
 16  }
 . 17  
18 is  class the MyThread the extends the Thread {
 . 19      @Override
 20 is      public  void RUN () {
 21 is          // super.run (); 
22 is          System.out.println ( "hellow_world!" );
 23 is      }
 24 }

2. Option II: Implementing runnable.

 1 //2. 实现runnable:Thread(Runnable target)
 2 public class ThreadCreateDemo1 {
 3     public static void main(String[] args) {
 4         MyRunnable runnable = new MyRunnable();
 5         MyRunnable runnable1 = new MyRunnable();
 6         MyRunnable runnable2 = new MyRunnable();
 7         MyRunnable runnable3 = new MyRunnable();
 8        new Thread(runnable).start();
 9        new Thread(runnable1).start();
10        new Thread(runnable2).start();
11        new Thread(runnable3).start();
12        
13      }
14 }
15 
16 class MyRunnable implements Runnable {
17     public void run() {
18         System.out.println("通过Runnable创建的线程!");
19     }
20 }
21  

 

 

 

 

 

The benefits of using inheritance is to facilitate mass participation, you can add member variables in a subclass inside, set the parameters set by the method or constructor is passed through, but if you use Runnable way, you can only use the main thread of which is declared as final variable. Bad is that Java does not support multiple inheritance, if inherited Thread class, subclass can not inherit from other classes, but Runable is not the limit. The first two ways no way to get the job return results, but Callable ways

 

Guess you like

Origin www.cnblogs.com/mengbin0546/p/12598653.html