java實(shí)現(xiàn)Runnable接口適合資源的共享
本文為大家分享了java實(shí)現(xiàn)Runnable接口適合資源的共享,供大家參考,具體內(nèi)容如下
Java當(dāng)中,創(chuàng)建線程通常用兩種方式:
1、繼承Thread類
2、實(shí)現(xiàn)Runnable接口
但是在通常的開發(fā)當(dāng)中,一般會(huì)選擇實(shí)現(xiàn)Runnable接口,原因有二:
1.避免單繼承的局限,在Java當(dāng)中一個(gè)類可以實(shí)現(xiàn)多個(gè)接口,但只能繼承一個(gè)類
2.適合資源的共享
原因1我們經(jīng)常聽到,但是2是什么呢?下面用一個(gè)例子來解釋:
有5張票,分兩個(gè)窗口賣:
繼承Thread類:
public class ThreadDemo { public static void main(String[] args) { HelloThread t1 = new HelloThread(); t1.setName("一號(hào)窗口"); t1.start(); HelloThread t2 = new HelloThread(); t2.setName("二號(hào)窗口"); 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; } } } }
運(yùn)行結(jié)果:
很明顯,這樣達(dá)不到我們想要的結(jié)果,這樣兩個(gè)窗口在同時(shí)賣票,互不干涉。
實(shí)現(xiàn)Thread類:
public class ThreadDemo { public static void main(String[] args) { HelloThread t = new HelloThread(); Thread thread1 = new Thread(t, "1號(hào)窗口"); thread1.start(); Thread thread2 = new Thread(t, "2號(hào)窗口"); 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; } } } }
運(yùn)行結(jié)果:
這樣兩個(gè)窗口就共享了5張票,因?yàn)橹划a(chǎn)生了一個(gè)HelloThread對(duì)象,一個(gè)對(duì)象里邊有一個(gè)屬性,這樣兩個(gè)線程同時(shí)在操作一個(gè)屬性,運(yùn)行同一個(gè)run方法。
這樣就達(dá)到了資源的共享。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- 詳解Java中Thread 和Runnable區(qū)別
- Java多線程實(shí)現(xiàn)Runnable方式
- 淺析Java中Runnable和Thread的區(qū)別
- Java 線程對(duì)比(Thread,Runnable,Callable)實(shí)例詳解
- java實(shí)現(xiàn)多線程的兩種方式繼承Thread類和實(shí)現(xiàn)Runnable接口的方法
- java線程之使用Runnable接口創(chuàng)建線程的方法
- JAVA多線程Thread和Runnable的實(shí)現(xiàn)
- Java向Runnable線程傳遞參數(shù)方法實(shí)例解析
相關(guān)文章
在springboot項(xiàng)目中同時(shí)接收文件和多個(gè)參數(shù)的方法總結(jié)
在開發(fā)接口中,遇到了需要同時(shí)接收文件和多個(gè)參數(shù)的情況,可以有多種方式實(shí)現(xiàn)文件和參數(shù)的同時(shí)接收,文中給大家介紹了兩種實(shí)現(xiàn)方法,感興趣的同學(xué)跟著小編一起來看看吧2023-08-08基于FeignException$InternalServerError的解決方案
這篇文章主要介紹了FeignException$InternalServerError的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06解決Eclipse配置Tomcat出現(xiàn)Cannot create a server using the selected
這篇文章主要介紹了解決Eclipse配置Tomcat出現(xiàn)Cannot create a server using the selected type錯(cuò)誤的相關(guān)資料,需要的朋友可以參考下2017-02-02springboot?vue項(xiàng)目管理后端實(shí)現(xiàn)接口新增
這篇文章主要為大家介紹了springboot?vue項(xiàng)目管理后端實(shí)現(xiàn)接口新增,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05深入解析Java多態(tài)進(jìn)階學(xué)習(xí)
java的動(dòng)態(tài)綁定機(jī)制非常重要。這篇文章將帶大家更深入的學(xué)習(xí)一下Java的多態(tài),文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)Java有一定幫助,需要的可以參考一下2022-07-07