一、線程基礎、線程之間的共享和協作(1)


實現線程的方式
1 繼承thread類                             單繼承,繼承thread類后,無法繼承其他類
2 實現runnable接口                      可以實現多個接口     無返回值
3 實現Callable接口通過FutureTask包裝器來創建Thread線程               有返回值

 

 1 package com.xiangxue.ch1;
 2 
 3 import java.util.concurrent.Callable;
 4 import java.util.concurrent.ExecutionException;
 5 import java.util.concurrent.FutureTask;
 6 
 7 public class NewThread {
 8     /**
 9      * 擴展自Thread類
10      * @param args
11      */
12     private static class MyThread extends Thread{
13         public void run(){
14             System.out.println("I am extends Thread");
15         }
16     }
17     
18     /**
19      * 實現Runnable接口
20      * @param args
21      */
22     private static class UseRun implements Runnable{
23         @Override
24         public void run() {
25             System.out.println("I am impelments Runnable;");
26         }
27     }
28     
29     /**
30      * 實現Callable接口,有返回值
31      * @param args
32      */
33     private static class UseCall implements Callable<String>{
34 
35         @Override
36         public String call() throws Exception {
37             System.out.println("I am impelments Callable;");
38             return "CallResult";
39         }
40     }
41     
42     
43     public static void main(String[] args) throws InterruptedException, ExecutionException {
44         MyThread myThread = new MyThread();
45         myThread.start();
46         
47         UseRun run = new UseRun();
48         new Thread(run).start();
49         
50         UseCall useCall = new UseCall();
51         FutureTask<String> futureTask = new FutureTask<>(useCall);
52         new Thread(futureTask).start();
53         System.out.println(futureTask.get());
54     }
55 
56 }
打印信息
I am extends Thread I am impelments Runnable; I am impelments Callable; CallResult

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM