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)文章
SpringBoot 過(guò)濾器, 攔截器, 監(jiān)聽器的具體使用
本文主要介紹了SpringBoot 過(guò)濾器, 攔截器, 監(jiān)聽器的具體使用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05
Java之MyBatis的Dao方式以及Dao動(dòng)態(tài)代理詳解
這篇文章主要介紹了Java之MyBatis的Dao方式以及Dao動(dòng)態(tài)代理詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12
Java集合Map常見問(wèn)題_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要為大家詳細(xì)整理了Java集合Map常見問(wèn)題,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05
Springboot集成ClickHouse及應(yīng)用場(chǎng)景分析
這篇文章主要介紹了Springboot集成ClickHouse的實(shí)例代碼,本文通過(guò)應(yīng)用場(chǎng)景實(shí)例代碼介紹了整合springboot的詳細(xì)過(guò)程,感興趣的朋友跟隨小編一起看看吧2022-02-02
SpringBoot跨系統(tǒng)單點(diǎn)登陸的實(shí)現(xiàn)方法
這篇文章主要介紹了SpringBoot跨系統(tǒng)單點(diǎn)登陸的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08

