一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服務(wù)器之家 - 編程語言 - JAVA教程 - 詳解三種java實現(xiàn)多線程的方式

詳解三種java實現(xiàn)多線程的方式

2020-01-02 14:06korelAK JAVA教程

數(shù)據(jù)時代的到來,多線程一直都是比較關(guān)心的問題之一,這篇文章介紹了JAVA實現(xiàn)多線程的三種方法,有需要的朋友可以參考一下

java中實現(xiàn)多線程的方法有兩種:繼承Thread類和實現(xiàn)runnable接口

1.繼承Thread類,重寫父類run()方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class thread1 extends Thread {
 
   public void run() {
       for (int i = 0; i < 10000; i++) {
           System.out.println("我是線程"+this.getId());
       }
   }
 
   public static void main(String[] args) {
       thread1 th1 = new thread1();
       thread1 th2 = new thread1();
       th1.run();
       th2.run();
   }
  }

run()方法只是普通的方法,是順序執(zhí)行的,即th1.run()執(zhí)行完成后才執(zhí)行th2.run(),這樣寫只用一個主線程。多線程就失去了意義,所以應(yīng)該用start()方法來啟動線程,start()方法會自動調(diào)用run()方法。上述代碼改為:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class thread1 extends Thread {
     
    public void run() {
        for (int i = 0; i < 10000; i++) {
            System.out.println("我是線程"+this.getId());
        }
    }
 
    public static void main(String[] args) {
        thread1 th1 = new thread1();
        thread1 th2 = new thread1();
        th1.start();
        th2.start();
    }
}

通過start()方法啟動一個新的線程。這樣不管th1.start()調(diào)用的run()方法是否執(zhí)行完,都繼續(xù)執(zhí)行th2.start()如果下面有別的代碼也同樣不需要等待th2.start()執(zhí)行完成,而繼續(xù)執(zhí)行。(輸出的線程id是無規(guī)則交替輸出的)

2.實現(xiàn)runnable接口

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class thread2 implements Runnable {
 
    public String ThreadName;
     
    public thread2(String tName){
        ThreadName = tName;
    }
     
     
    public void run() {
        for (int i = 0; i < 10000; i++) {
            System.out.println(ThreadName);
        }
    }
     
    public static void main(String[] args) {
        thread2 th1 = new thread2("線程A");
        thread2 th2 = new thread2("線程B");
        th1.run();
        th2.run();
    }
}

和Thread的run方法一樣Runnable的run只是普通方法,在main方法中th2.run()必須等待th1.run()執(zhí)行完成后才能執(zhí)行,程序只用一個線程。要多線程的目的,也要通過Thread的start()方法(注:runnable是沒有start方法)。上述代碼修改為:

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class thread2 implements Runnable {
 
    public String ThreadName;
     
    public thread2(String tName){
        ThreadName = tName;
    }
     
     
    public void run() {
        for (int i = 0; i < 10000; i++) {
            System.out.println(ThreadName);
        }
    }
     
    public static void main(String[] args) {
        thread2 th1 = new thread2("線程A");
        thread2 th2 = new thread2("Thread-B");
        Thread myth1 = new Thread(th1);
        Thread myth2 = new Thread(th2);
        myth1.start();
        myth2.start();
    }
}

3.使用ExecutorService、Callable、Future實現(xiàn)有返回結(jié)果的多線程(JDK5.0以后)
可返回值的任務(wù)必須實現(xiàn)Callable接口,類似的,無返回值的任務(wù)必須Runnable接口。執(zhí)行Callable任務(wù)后,可以獲取一個Future的對象,在該對象上調(diào)用get就可以獲取到Callable任務(wù)返回的Object了,再結(jié)合線程池接口ExecutorService就可以實現(xiàn)傳說中有返回結(jié)果的多線程了。下面提供了一個完整的有返回結(jié)果的多線程測試?yán)樱贘DK1.5下驗證過沒問題可以直接使用。代碼如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import java.util.concurrent.*;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
  
/**
* 有返回值的線程
*/
@SuppressWarnings("unchecked")
public class Test {
public static void main(String[] args) throws ExecutionException,
  InterruptedException {
  System.out.println("----程序開始運行----");
  Date date1 = new Date();
  
  int taskSize = 5;
  // 創(chuàng)建一個線程池
  ExecutorService pool = Executors.newFixedThreadPool(taskSize);
  // 創(chuàng)建多個有返回值的任務(wù)
  List<Future> list = new ArrayList<Future>();
  for (int i = 0; i < taskSize; i++) {
  Callable c = new MyCallable(i + " ");
  // 執(zhí)行任務(wù)并獲取Future對象
  Future f = pool.submit(c);
  // System.out.println(">>>" + f.get().toString());
  list.add(f);
  }
  // 關(guān)閉線程池
  pool.shutdown();
  
  // 獲取所有并發(fā)任務(wù)的運行結(jié)果
  for (Future f : list) {
  // 從Future對象上獲取任務(wù)的返回值,并輸出到控制臺
  System.out.println(">>>" + f.get().toString());
  }
  
  Date date2 = new Date();
  System.out.println("----程序結(jié)束運行----,程序運行時間【"
   + (date2.getTime() - date1.getTime()) + "毫秒】");
}
}
  
class MyCallable implements Callable<Object> {
private String taskNum;
  
MyCallable(String taskNum) {
  this.taskNum = taskNum;
}
  
public Object call() throws Exception {
  System.out.println(">>>" + taskNum + "任務(wù)啟動");
  Date dateTmp1 = new Date();
  Thread.sleep(1000);
  Date dateTmp2 = new Date();
  long time = dateTmp2.getTime() - dateTmp1.getTime();
  System.out.println(">>>" + taskNum + "任務(wù)終止");
  return taskNum + "任務(wù)返回運行結(jié)果,當(dāng)前任務(wù)時間【" + time + "毫秒】";
}
}

 

代碼說明:
上述代碼中Executors類,提供了一系列工廠方法用于創(chuàng)先線程池,返回的線程池都實現(xiàn)了ExecutorService接口。
public static ExecutorService newFixedThreadPool(int nThreads)
創(chuàng)建固定數(shù)目線程的線程池。
public static ExecutorService newCachedThreadPool()
創(chuàng)建一個可緩存的線程池,調(diào)用execute 將重用以前構(gòu)造的線程(如果線程可用)。如果現(xiàn)有線程沒有可用的,則創(chuàng)建一個新線程并添加到池中。終止并從緩存中移除那些已有 60 秒鐘未被使用的線程。
public static ExecutorService newSingleThreadExecutor()
創(chuàng)建一個單線程化的Executor。
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
創(chuàng)建一個支持定時及周期性的任務(wù)執(zhí)行的線程池,多數(shù)情況下可用來替代Timer類。
ExecutoreService提供了submit()方法,傳遞一個Callable,或Runnable,返回Future。如果Executor后臺線程池還沒有完成Callable的計算,這調(diào)用返回Future對象的get()方法,會阻塞直到計算完成。

總結(jié):實現(xiàn)java多線程的2種方式,runable是接口,thread是類,runnable只提供一個run方法,建議使用runable實現(xiàn) java多線程,不管如何,最終都需要通過thread.start()來使線程處于可運行狀態(tài)。第三種方法是聽群里的兄弟們介紹的,所以就百度補(bǔ)上了。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 亚洲AV久久无码精品九号软件 | 国产成人高清精品免费5388密 | 日韩欧美一区二区三区视频 | 91传媒制片厂制作传媒破解版 | 亚洲乱亚洲23p女 | 亚洲日韩男人网在线 | 青青草久| 我半夜摸妺妺的奶C了她软件 | 精品国产欧美一区二区 | 久久99视热频国只有精品 | avtt天堂在线| 娇小8一12xxxx第一次 | 成人免费视频播放 | 亚洲精品久久玖玖玖玖 | 精品久久成人免费第三区 | 欧美精品国产一区二区 | 99久久精品国语对白 | 男女做性视频 | 美女隐私部位视频网站 | 第一次破女视频国产一级 | 高清麻生希在线 | 国产高清不卡视频在线播放 | 亚洲日韩男人网在线 | 搞逼综合网 | 日韩大片在线播放 | 久久伊人影视 | 32pao强力打造免费高速高清 | 91果冻制片厂天美传媒 | 亚洲爱v| 亚洲福利天堂网福利在线观看 | 精品一区久久 | 五月色婷婷在线影院 | 热色综合 | 高清视频免费 | 亚洲欧美综合在线观看 | yy3341殇情影院理论片 | 1024免费福利永久观看网站 | 丝瓜视频看污片 | 欧美一级欧美三级在线 | 精品一区二区免费视频蜜桃网 | 99精品影视 |