thread和runnable區(qū)別
執(zhí)行多線(xiàn)程操作可以選擇
繼承thread類(lèi)
實(shí)現(xiàn)runnable接口
1.繼承thread類(lèi)
以賣(mài)票窗口舉例,一共5張票,由3個(gè)窗口進(jìn)行售賣(mài)(3個(gè)線(xiàn)程)。
代碼:
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--); } } } |
執(zhí)行結(jié)果:
窗口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
結(jié)果一共賣(mài)出了5*3=15張票,這違背了"5張票"的初衷。
造成此現(xiàn)象的原因就是:
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(); |
一共創(chuàng)建了3個(gè)mythreadtest對(duì)象,而這3個(gè)對(duì)象的資源不是共享的,即各自定義的ticket=5是不會(huì)共享的,因此3個(gè)線(xiàn)程都執(zhí)行了5次循環(huá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
|
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--); } } } |
結(jié)果:
窗口1 = 5
窗口1 = 2
窗口3 = 4
窗口2 = 3
窗口1 = 1
結(jié)果賣(mài)出了預(yù)期的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(); |
只創(chuàng)建了一個(gè)myrunnabletest對(duì)象,而3個(gè)thread線(xiàn)程都以同一個(gè)myrunnabletest來(lái)啟動(dòng),所以他們的資源是共享的。
以上所述是小編給大家介紹的多線(xiàn)程及runable 和thread的區(qū)別詳解整合,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)服務(wù)器之家網(wǎng)站的支持!
原文鏈接:https://blog.csdn.net/qq_43499096/article/details/89048216