在java中,有三種方法可以實現多線程。第一種方法:繼承Thread類,重寫run函數。第二種方法:實現Runnable接口,重寫run函數。第三種方法:實現Callable接口,重寫call函數。本文章將通過實例講解這三種方法如何實現多線程。需要的可以參考一下。
(1)繼承Thread類,重寫run函數。
1
2
3
4
|
class xx extends Thread{ public void run(){ Thread.sleep( 1000 ) //線程休眠1000毫秒,sleep使線程進入Block狀態,并釋放資源 }} |
開啟線程:
對象.start() //啟動線程,run函數運行
(2)實現Runnable接口,代碼如下
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
|
class MyThread implements Runnable { private String name; public MyThread(String name) { super (); this .name = name; } @Override public void run() { for ( int i = 0 ; i < 200 ; i++) { System.out.println( "Thread" +name+ "--->" +i); } } } public class ThreadDemo { public static void main(String[] args) { MyThread a = new MyThread( "a" ); MyThread b = new MyThread( "b" ); MyThread c = new MyThread( "c" ); new Thread(a).start(); new Thread(b).start(); new Thread(c).start(); } } |
(3)實現Callable接口,重寫call函數
Callable是類似于Runnable的接口,實現Callable接口的類和實現Runnable的類都是可被其它線程執行的任務。
Callable和Runnable有幾點不同:
- Callable規定的方法是call(),而Runnable規定的方法是run().
- Callable的任務執行后可返回值,而Runnable的任務是不能返回值的
- call()方法可拋出異常,而run()方法是不能拋出異常的。
- 運行Callable任務可拿到一個Future對象,Future表示異步計算的結果。它提供了檢查計算是否完成的方法,以等待計算的完成,并檢索計算的結果.通過Future對象可了解任務執行情況,可取消任務的執行,還可獲取任務執行的結果
Java Callable 代碼示例:
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
|
class TaskWithResult implements Callable<String> { private int id; public TaskWithResult( int id) { this .id = id; } @Override public String call() throws Exception { return "result of TaskWithResult " + id; } } public class CallableTest { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService exec = Executors.newCachedThreadPool(); ArrayList<Future<String>> results = new ArrayList<Future<String>>(); //Future 相當于是用來存放Executor執行的結果的一種容器 for ( int i = 0 ; i < 10 ; i++) { results.add(exec.submit( new TaskWithResult(i))); } for (Future<String> fs : results) { if (fs.isDone()) { System.out.println(fs.get()); } else { System.out.println( "Future result is not yet complete" ); } } exec.shutdown(); } } |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!