本文為大家分享了java實現(xiàn)runnable接口適合資源的共享,供大家參考,具體內(nèi)容如下
java當(dāng)中,創(chuàng)建線程通常用兩種方式:
1、繼承thread類
2、實現(xiàn)runnable接口
但是在通常的開發(fā)當(dāng)中,一般會選擇實現(xiàn)runnable接口,原因有二:
1.避免單繼承的局限,在java當(dāng)中一個類可以實現(xiàn)多個接口,但只能繼承一個類
2.適合資源的共享
原因1我們經(jīng)常聽到,但是2是什么呢?下面用一個例子來解釋:
有5張票,分兩個窗口賣:
繼承thread類:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
public class threaddemo { public static void main(string[] args) { hellothread t1 = new hellothread(); t1.setname( "一號窗口" ); t1.start(); hellothread t2 = new hellothread(); t2.setname( "二號窗口" ); t2.start(); } } class hellothread extends thread{ private int ticket = 5 ; public void run() { while ( true ){ system.out.println( this .getname()+(ticket--)); if (ticket< 1 ) { break ; } } } } |
運行結(jié)果:
很明顯,這樣達(dá)不到我們想要的結(jié)果,這樣兩個窗口在同時賣票,互不干涉。
實現(xiàn)thread類:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public class threaddemo { public static void main(string[] args) { hellothread t = new hellothread(); thread thread1 = new thread(t, "1號窗口" ); thread1.start(); thread thread2 = new thread(t, "2號窗口" ); thread2.start(); } } class hellothread implements runnable{ private int ticket = 5 ; public void run() { while ( true ){ system.out.println(thread.currentthread().getname()+(ticket--)); if (ticket< 1 ) { break ; } } } } |
運行結(jié)果:
這樣兩個窗口就共享了5張票,因為只產(chǎn)生了一個hellothread對象,一個對象里邊有一個屬性,這樣兩個線程同時在操作一個屬性,運行同一個run方法。
這樣就達(dá)到了資源的共享。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/xusheng_Mr/article/details/61938216