java Runnable接口創(chuàng)建線程
java Runnable接口創(chuàng)建線程
創(chuàng)建一個線程,最簡單的方法是創(chuàng)建一個實現(xiàn)Runnable接口的類。
為了實現(xiàn)Runnable,一個類只需要執(zhí)行一個方法調(diào)用run(),聲明如下:
public void run()
你可以重寫該方法,重要的是理解的run()可以調(diào)用其他方法,使用其他類,并聲明變量,就像主線程一樣。
在創(chuàng)建一個實現(xiàn)Runnable接口的類之后,你可以在類中實例化一個線程對象。
Thread定義了幾個構(gòu)造方法,下面的這個是我們經(jīng)常使用的:
Thread(Runnable threadOb,String threadName);
這里,threadOb 是一個實現(xiàn)Runnable 接口的類的實例,并且 threadName指定新線程的名字。
新線程創(chuàng)建之后,你調(diào)用它的start()方法它才會運行。
void start();
實例
下面是一個創(chuàng)建線程并開始讓它執(zhí)行的實例:
// 創(chuàng)建一個新的線程 class NewThread implements Runnable { Thread t; NewThread() { // 創(chuàng)建第二個新線程 t = new Thread(this, "Demo Thread"); System.out.println("Child thread: " + t); t.start(); // 開始線程 } // 第二個線程入口 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)建一個新線程 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."); } }
編譯以上程序運行結(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.
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
Java中實現(xiàn)Comparator接口和用法實例(簡明易懂)
這篇文章主要介紹了Java中實現(xiàn)Comparator接口和用法實例(簡明易懂),本文給出實現(xiàn)Comparator接口的實例和使用這個接口的代碼實例,需要的朋友可以參考下2015-05-05springboot中實現(xiàn)通過后臺創(chuàng)建臨時表
這篇文章主要介紹了springboot中實現(xiàn)通過后臺創(chuàng)建臨時表操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07基于SpringCloudGateway實現(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)提供一種簡單而有效的統(tǒng)一的API路由管理方式,對SpringCloudGateway實現(xiàn)微服務(wù)網(wǎng)關(guān)相關(guān)知識感興趣的朋友一起看看吧2021-12-12SpringBoot封裝響應(yīng)處理超詳細(xì)講解
這篇文章主要介紹了SpringBoot封裝響應(yīng)處理,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2022-12-12Sublime Text 打開Java文檔中文亂碼的解決方案
這篇文章主要介紹了Sublime Text 中文亂碼的解決方案,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下2020-12-12