thread和runnable區別
執行多線程操作可以選擇
繼承thread類
實現runnable接口
1.繼承thread類
以賣票窗口舉例,一共5張票,由3個窗口進行售賣(3個線程)。
代碼:
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
|
package thread; public class threadtest { public static void main(string[] args) { mythreadtest mt1 = new mythreadtest( "窗口1" ); mythreadtest mt2 = new mythreadtest( "窗口2" ); mythreadtest mt3 = new mythreadtest( "窗口3" ); mt1.start(); mt2.start(); mt3.start(); } } class mythreadtest extends thread{ private int ticket = 5 ; private string name; public mythreadtest(string name){ this .name = name; } public void run(){ while ( true ){ if (ticket < 1 ){ break ; } system.out.println(name + " = " + ticket--); } } } |
執行結果:
窗口1 = 5
窗口1 = 4
窗口1 = 3
窗口1 = 2
窗口1 = 1
窗口2 = 5
窗口3 = 5
窗口2 = 4
窗口3 = 4
窗口3 = 3
窗口3 = 2
窗口3 = 1
窗口2 = 3
窗口2 = 2
窗口2 = 1
結果一共賣出了5*3=15張票,這違背了"5張票"的初衷。
造成此現象的原因就是:
1
2
3
4
5
6
|
mythreadtest mt1 = new mythreadtest( "窗口1" ); mythreadtest mt2 = new mythreadtest( "窗口2" ); mythreadtest mt3 = new mythreadtest( "窗口3" ); mt1.start(); mt2.start(); mt3.start(); |
一共創建了3個mythreadtest對象,而這3個對象的資源不是共享的,即各自定義的ticket=5是不會共享的,因此3個線程都執行了5次循環操作。
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
|
package thread; public class runnabletest { public static void main(string[] args) { myrunnabletest mt = new myrunnabletest(); thread mt1 = new thread(mt, "窗口1" ); thread mt2 = new thread(mt, "窗口2" ); thread mt3 = new thread(mt, "窗口3" ); mt1.start(); mt2.start(); mt3.start(); } } class myrunnabletest implements runnable{ private int ticket = 5 ; public void run(){ while ( true ){ if (ticket < 1 ){ break ; } system.out.println(thread.currentthread().getname() + " = " + ticket--); } } } |
結果:
窗口1 = 5
窗口1 = 2
窗口3 = 4
窗口2 = 3
窗口1 = 1
結果賣出了預期的5張票。
原因在于:
1
2
3
4
5
6
7
|
myrunnabletest mt = new myrunnabletest(); thread mt1 = new thread(mt, "窗口1" ); thread mt2 = new thread(mt, "窗口2" ); thread mt3 = new thread(mt, "窗口3" ); mt1.start(); mt2.start(); mt3.start(); |
只創建了一個myrunnabletest對象,而3個thread線程都以同一個myrunnabletest來啟動,所以他們的資源是共享的。
以上所述是小編給大家介紹的多線程及runable 和thread的區別詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://blog.csdn.net/qq_43499096/article/details/89048216