本文為大家分享了java實現runnable接口適合資源的共享,供大家參考,具體內容如下
java當中,創建線程通常用兩種方式:
1、繼承thread類
2、實現runnable接口
但是在通常的開發當中,一般會選擇實現runnable接口,原因有二:
1.避免單繼承的局限,在java當中一個類可以實現多個接口,但只能繼承一個類
2.適合資源的共享
原因1我們經常聽到,但是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 ; } } } } |
運行結果:
很明顯,這樣達不到我們想要的結果,這樣兩個窗口在同時賣票,互不干涉。
實現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 ; } } } } |
運行結果:
這樣兩個窗口就共享了5張票,因為只產生了一個hellothread對象,一個對象里邊有一個屬性,這樣兩個線程同時在操作一個屬性,運行同一個run方法。
這樣就達到了資源的共享。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/xusheng_Mr/article/details/61938216