java Runnable接口創(chuàng)建線程
java Runnable接口創(chuàng)建線程
創(chuàng)建一個(gè)線程,最簡(jiǎn)單的方法是創(chuàng)建一個(gè)實(shí)現(xiàn)Runnable接口的類。
為了實(shí)現(xiàn)Runnable,一個(gè)類只需要執(zhí)行一個(gè)方法調(diào)用run(),聲明如下:
public void run()
你可以重寫該方法,重要的是理解的run()可以調(diào)用其他方法,使用其他類,并聲明變量,就像主線程一樣。
在創(chuàng)建一個(gè)實(shí)現(xiàn)Runnable接口的類之后,你可以在類中實(shí)例化一個(gè)線程對(duì)象。
Thread定義了幾個(gè)構(gòu)造方法,下面的這個(gè)是我們經(jīng)常使用的:
Thread(Runnable threadOb,String threadName);
這里,threadOb 是一個(gè)實(shí)現(xiàn)Runnable 接口的類的實(shí)例,并且 threadName指定新線程的名字。
新線程創(chuàng)建之后,你調(diào)用它的start()方法它才會(huì)運(yùn)行。
void start();
實(shí)例
下面是一個(gè)創(chuàng)建線程并開始讓它執(zhí)行的實(shí)例:
// 創(chuàng)建一個(gè)新的線程 class NewThread implements Runnable { Thread t; NewThread() { // 創(chuàng)建第二個(gè)新線程 t = new Thread(this, "Demo Thread"); System.out.println("Child thread: " + t); t.start(); // 開始線程 } // 第二個(gè)線程入口 public void run() { try { for(int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); // 暫停線程 Thread.sleep(50); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("Exiting child thread."); } } public class ThreadDemo { public static void main(String args[]) { new NewThread(); // 創(chuàng)建一個(gè)新線程 try { for(int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(100); } } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } }
編譯以上程序運(yùn)行結(jié)果如下:
Child thread: Thread[Demo Thread,5,main] Main Thread: 5 Child Thread: 5 Child Thread: 4 Main Thread: 4 Child Thread: 3 Child Thread: 2 Main Thread: 3 Child Thread: 1 Exiting child thread. Main Thread: 2 Main Thread: 1 Main thread exiting.
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
Java中實(shí)現(xiàn)Comparator接口和用法實(shí)例(簡(jiǎn)明易懂)
這篇文章主要介紹了Java中實(shí)現(xiàn)Comparator接口和用法實(shí)例(簡(jiǎn)明易懂),本文給出實(shí)現(xiàn)Comparator接口的實(shí)例和使用這個(gè)接口的代碼實(shí)例,需要的朋友可以參考下2015-05-05Java實(shí)現(xiàn)五子棋網(wǎng)絡(luò)版
這篇文章主要為大家詳細(xì)介紹了基于Java編寫的網(wǎng)絡(luò)五子棋,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-03-03springboot中實(shí)現(xiàn)通過后臺(tái)創(chuàng)建臨時(shí)表
這篇文章主要介紹了springboot中實(shí)現(xiàn)通過后臺(tái)創(chuàng)建臨時(shí)表操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07java實(shí)現(xiàn)圖片裁切的工具類實(shí)例
這篇文章主要介紹了java實(shí)現(xiàn)圖片裁切的工具類實(shí)例,涉及Java針對(duì)圖片的讀取、修改等相關(guān)操作技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-11-11基于SpringCloudGateway實(shí)現(xiàn)微服務(wù)網(wǎng)關(guān)的方式
Spring?Cloud?Gateway是Spring?官方基于Spring?5.0,Spring?Boot?2.0和Project?Reactor?等技術(shù)開發(fā)的網(wǎng)關(guān),旨在為微服務(wù)架構(gòu)提供一種簡(jiǎn)單而有效的統(tǒng)一的API路由管理方式,對(duì)SpringCloudGateway實(shí)現(xiàn)微服務(wù)網(wǎng)關(guān)相關(guān)知識(shí)感興趣的朋友一起看看吧2021-12-12SpringBoot封裝響應(yīng)處理超詳細(xì)講解
這篇文章主要介紹了SpringBoot封裝響應(yīng)處理,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2022-12-12Sublime Text 打開Java文檔中文亂碼的解決方案
這篇文章主要介紹了Sublime Text 中文亂碼的解決方案,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下2020-12-12