java Runnable接口如何創建線程
- java語言
- 關注:5.58K次
導語:編寫多線程程序是為了實現多任務的併發執行,從而能夠更好地與用户交互。下面是java Runnable接口創建線程的相關資料,歡迎閲讀:
java Runnable接口創建線程
創建一個線程,最簡單的方法是創建一個實現Runnable接口的類。
為了實現Runnable,一個類只需要執行一個方法調用run(),聲明如下:
public void run()
你可以重寫該方法,重要的是理解的run()可以調用其他方法,使用其他類,並聲明變量,就像主線程一樣。
在創建一個實現Runnable接口的`類之後,你可以在類中實例化一個線程對象。
Thread定義了幾個構造方法,下面的這個是我們經常使用的:
Thread(Runnable threadOb,String threadName);
這裏,threadOb 是一個實現Runnable 接口的類的實例,並且 threadName指定新線程的名字。
新線程創建之後,你調用它的start()方法它才會運行。
void start();
實例
下面是一個創建線程並開始讓它執行的實例:
// 創建一個新的線程
class NewThread implements Runnable {
Thread t;
NewThread() {
// 創建第二個新線程
t = new Thread(this, "Demo Thread");
tln("Child thread: " + t);
t(); // 開始線程
}
// 第二個線程入口
public void run() {
try {
for(int i = 5; i > 0; i--) {
tln("Child Thread: " + i);
// 暫停線程
p(50);
}
} catch (InterruptedException e) {
tln("Child interrupted.");
}
tln("Exiting child thread.");
}
}
public class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // 創建一個新線程
try {
for(int i = 5; i > 0; i--) {
tln("Main Thread: " + i);
p(100);
}
} catch (InterruptedException e) {
tln("Main thread interrupted.");
}
tln("Main thread exiting.");
}
}
編譯以上程序運行結果如下:
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.
- 文章版權屬於文章作者所有,轉載請註明 https://xuezhezhai.com/zh-hk/jsj/java/nr2ez.html