多線程三種主要實現方式:繼承Thread類,實現Runnable接口、Callable和Futrue。
一、簡單實現
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
|
import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; public class T02_HowToCreateThread { //1.繼承Thread類 static class MyThread extends Thread{ @Override public void run() { System.out.println( "MyThread-->" ); } } //3.實現Runnable接口 static class MyRun implements Runnable{ @Override public void run() { System.out.println( "MyRunable-->" ); } } //4.實現Callable接口 static class MyCall implements Callable{ @Override public Object call() throws Exception { System.out.println( "myCallable-->" ); return 1 ; } } public static void main(String[] args) throws ExecutionException, InterruptedException { //1.繼承Thread類 new MyThread().start(); //2.lambda與繼承Thread類類//1.繼承Thread類似,最簡單 new Thread(()->{ System.out.println( "lambda-->" ); }).start(); //3.實現Runnable接口 new Thread( new MyRun()).start(); new Thread( new Runnable() { @Override public void run() { System.out.println( "simple->Runnable" ); } }).start(); //4.實現Callable接口,并用包裝器FutureTask來同時實現Runable、Callable兩個接口,可帶返回結果 MyCall mycall = new MyCall(); FutureTask futureTask = new FutureTask(mycall); new Thread(futureTask).start(); System.out.println(futureTask.get()); } } |
二、使用ExecutorService、Callable和Future一起實現帶返回值
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
|
import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; /** * 使用ExecutorsService、Callable、Future來實現多個帶返回值的線程 */ public class T02_HowToCreateThread02 { static class MyCallable implements Callable{ private int taskNum; public MyCallable( int taskNum){ this .taskNum = taskNum; } @Override public Object call() throws Exception { System.out.println( "任務" +taskNum); return "MyCallable.call()-->task" +taskNum; } } public static void main(String[] args) throws ExecutionException, InterruptedException { int num = 5 ; //創建一個線程池 ExecutorService pool = Executors.newFixedThreadPool(num); List<Future> futureList = new ArrayList<Future>(); for ( int i = 0 ; i < num; i++){ MyCallable mc = new MyCallable(i); //執行任務,并返回值 Future future = pool.submit(mc); futureList.add(future); } pool.shutdown(); for (Future f: futureList){ System.out.println(f.get()); } } } |
結果:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/helq/p/13264050.html