java創建線程主要有三種方式:繼承thread類創建線程、實現runnable接口創建線程和實現callable和future創建線程。
繼承thread類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class thread1 extends thread { @override public void run() { for ( int i = 0 ; i < 10 ; i++) { system.out.println(getname() + ": " + i); } } public static void main(string[] args) { for ( int i = 0 ; i < 10 ; i++) { system.out.println(thread.currentthread().getname() + ": " + i); if (i == 2 ) { new thread1().start(); new thread1().start(); } } } } |
實現runnable接口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public class thread2 implements runnable { @override public void run() { for ( int i = 0 ; i < 10 ; i++) { system.out.println(thread.currentthread().getname() + ": " + i); } } public static void main(string[] args) { for ( int i = 0 ; i < 10 ; i++) { system.out.println(thread.currentthread().getname() + ": " + i); if (i == 2 ) { thread2 thread2 = new thread2(); new thread(thread2).start(); new thread(thread2).start(); } } } } |
實現callable接口
futuretask類包裝callable對象時,封裝了callable對象的call()方法的返回值。
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
|
class thread3 implements callable { @override public integer call() throws exception { int i = 0 ; for (; i < 10 ; i++) { system.out.println(thread.currentthread().getname() + ": " + i); } return i; } public static void main(string[] args) { thread3 thread3 = new thread3(); futuretask<integer> futuretask = new futuretask<integer>(thread3); for ( int i = 0 ; i < 10 ; i++) { system.out.println(thread.currentthread().getname() + " :" + i); if (i == 2 ) { new thread(futuretask, "有返回值的線程" ).start(); } } try { system.out.println( "子線程返回值: " + futuretask.get()); } catch (interruptedexception e) { e.printstacktrace(); } catch (executionexception e) { e.printstacktrace(); } } } |
三種方式優缺點
采用實現接口(runnable和callable)的方式,線程類還可以繼承其他的類。實現接口的線程對象還可以用來創建多個線程,可以實現資源共享。缺點是不能使用this指針來獲取線程的名字等。
采用繼承thread類的方式,線程不能繼承其他的類,但是thread類中有getname方法,因為可以直接使用this.getname()來獲取當前線程的名字。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對服務器之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
原文鏈接:https://blog.csdn.net/sinat_28394909/article/details/84956184