1. 程式人生 > >創建線程的多種方式

創建線程的多種方式

width val throws i++ -c lis @service nds app

技術分享圖片

 1 public class Demo1 extends Thread{
 2     
 3     @Override
 4     public void run() {
 5         while(!interrupted()) {
 6             System.out.println(getName()+"線程執行了");
 7             try {
 8                 Thread.sleep(200);
 9             } catch (InterruptedException e) {
10                 // TODO Auto-generated catch block
11                 e.printStackTrace();
12             }
13             
14         }
15     }
16     
17     public static void main(String[] args) {
18         Demo1 d1 = new Demo1();
19         Demo1 d2 = new Demo1();
20         
21         d1.start();
22         d2.start();
23         
24         d1.interrupt();
25         
26     }
27     
28 
29 }

技術分享圖片

 1 public class Demo2 implements Runnable {
 2 
 3     @Override
 4     public void run() {
 5         while(true) {
 6             System.out.println("thread running ...");
 7         }
 8         
 9     }
10     
11     
12     public static void main(String[] args) {
13         Thread thread = new Thread(new Demo2());
14         thread.start();
15     }
16     
17 
18 }

技術分享圖片

public class Demo3 {
    
    public static void main(String[] args) {
        
      //繼承thread類子類方式
      /*new Thread() {
            public void run() {
                System.out.println("thread start ...");
            };
        }.start();
        */
        
        //實現runnable接口
/*        new Thread(new Runnable() {
            public void run() {
                System.out.println("thread start ...");
            }
        }).start();*/
        
        new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println("runnable");
                
            }
            
        }) {
            @Override
            public void run() {
            System.out.println("sub");
                
            }
        }.start();
        
        //sub 重寫了父類的run方法      
    }

技術分享圖片

 1 public class Demo4 implements Callable<Integer>{ //指定返回類型
 2     
 3     public static void main(String[] args) throws Exception {
 4         Demo4 d = new Demo4();
 5         //class FutureTask<V> implements Runnables RunnableFuture<V>
 6             //   --- interface RunnableFuture<V> extends Runnable,Future<V> 對線程任務進行封裝
 7         
 8         FutureTask<Integer> task = new FutureTask<>(d);
 9         
10         Thread t = new Thread(task);
11         t.start();
12         
13         Integer result = task.get();
14         System.out.println("線程執行結果為:"+result);
15     }
16 
17     @Override
18     public Integer call() throws  Exception {
19         System.out.println("正在進行緊張計算");
20         Thread.sleep(3000);
21         return 1;
22     }
23 
24 }

技術分享圖片

 1 public class Demo5 {
 2     
 3     
 4     public static void main(String[] args) {
 5         
 6         Timer timer = new Timer();
 7         
 8         // abstract class TimerTask implements Runnable 
 9         timer.schedule(new TimerTask() {
10             
11             @Override
12             public void run() {
13                 //實現定時任務
14                 System.out.println("timertask is running");
15             }
16         }, 0, 1000);
17         //java.util.Timer.schedule(TimerTask task, long delay, long period)
18         
19     }
20 
21 }

技術分享圖片

 1 public class Demo6 {
 2     
 3     public static void main(String[] args) {
 4         
 5         Executor threadPool = Executors.newFixedThreadPool(10);//固定容量的線程池
 6         
 7         for(int i = 0;i<10; i++ ) {
 8             threadPool.execute(new Runnable() {
 9 
10                 @Override
11                 public void run() {
12                     System.out.println(Thread.currentThread().getName());
13                 }
14             });
15         }
16     }
17 }

技術分享圖片

 1 public class Demo7 {
 2     
 3     public static void main(String[] args) {
 4         List<Integer> values = Arrays.asList(10,20,30,40);  //  Arrays.asList(array):將數組array轉化為List
 5         int res = new Demo7().add(values);
 6         System.out.println("計算結果為:"+res);
 7     }
 8     public int add(List<Integer> values) {
 9         values.parallelStream().forEach(System.out :: println);
10         return 0;
11         
12         //        30
13         //        20
14         //        10
15         //        40
16         //        計算結果為:0
17         //parallelStream 並行執行
18         // return values.parallelStream().mapToInt(a -> a).sum();
19         
20     }
21 
22 }

技術分享圖片

新建spring boot工程,pom 中引入spring-context依賴

//Config.java

@Configuration
@ComponentScan("com.roocon.thread.t1")
@EnableAsync
public class Config {

}

//DemoService

@Service public class DemoService { @Async public void a() { while(true) { System.out.println("a"); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @Async public void b() { while(true) { System.out.println("b"); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }

public class Main {
    
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(Config.class);
         DemoService ds = ac.getBean(DemoService.class);
         
         ds.a();
         ds.b();
        
    }

}

創建線程的多種方式