在java中,有三種方法可以實(shí)現(xiàn)多線程。第一種方法:繼承Thread類,重寫run函數(shù)。第二種方法:實(shí)現(xiàn)Runnable接口,重寫run函數(shù)。第三種方法:實(shí)現(xiàn)Callable接口,重寫call函數(shù)。本文章將通過實(shí)例講解這三種方法如何實(shí)現(xiàn)多線程。需要的可以參考一下。
(1)繼承Thread類,重寫run函數(shù)。
1
2
3
4
|
class xx extends Thread{ public void run(){ Thread.sleep( 1000 ) //線程休眠1000毫秒,sleep使線程進(jìn)入Block狀態(tài),并釋放資源 }} |
開啟線程:
對(duì)象.start() //啟動(dòng)線程,run函數(shù)運(yùn)行
(2)實(shí)現(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
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)實(shí)現(xiàn)Callable接口,重寫call函數(shù)
Callable是類似于Runnable的接口,實(shí)現(xiàn)Callable接口的類和實(shí)現(xiàn)Runnable的類都是可被其它線程執(zhí)行的任務(wù)。
Callable和Runnable有幾點(diǎn)不同:
- Callable規(guī)定的方法是call(),而Runnable規(guī)定的方法是run().
- Callable的任務(wù)執(zhí)行后可返回值,而Runnable的任務(wù)是不能返回值的
- call()方法可拋出異常,而run()方法是不能拋出異常的。
- 運(yùn)行Callable任務(wù)可拿到一個(gè)Future對(duì)象,F(xiàn)uture表示異步計(jì)算的結(jié)果。它提供了檢查計(jì)算是否完成的方法,以等待計(jì)算的完成,并檢索計(jì)算的結(jié)果.通過Future對(duì)象可了解任務(wù)執(zhí)行情況,可取消任務(wù)的執(zhí)行,還可獲取任務(wù)執(zhí)行的結(jié)果
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 相當(dāng)于是用來存放Executor執(zhí)行的結(jié)果的一種容器 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(); } } |
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!