關于線程池的內容,我們以后會詳細介紹;現在,先對的Thread和Runnable進行了解。本章內容包括:
Thread和Runnable的簡介
Thread和Runnable的異同點
Thread和Runnable的多線程的示例
Thread和Runnable簡介
Runnable 是一個接口,該接口中只包含了一個run()方法。它的定義如下:
public interface Runnable {
public abstract void run();
}
Runnable的作用,實現多線程。我們可以定義一個類A實現Runnable接口;然后,通過new Thread(new A())等方式新建線程。
Thread 是一個類。Thread本身就實現了Runnable接口。它的聲明如下:
public class Thread implements Runnable {}
Thread的作用,實現多線程。
Thread和Runnable的異同點
Thread 和 Runnable 的相同點:都是“多線程的實現方式”。
Thread 和 Runnable 的不同點:
Thread 是類,而Runnable是接口;Thread本身是實現了Runnable接口的類。我們知道“一個類只能有一個父類,但是卻能實現多個接口”,因此Runnable具有更好的擴展性。
此外,Runnable還可以用于“資源的共享”。即,多個線程都是基于某一個Runnable對象建立的,它們會共享Runnable對象上的資源。
通常,建議通過“Runnable”實現多線程!
Thread和Runnable的多線程示例
1. Thread的多線程示例
下面通過示例更好的理解Thread和Runnable,借鑒網上一個例子比較具有說服性的例子。
// ThreadTest.java 源碼
class MyThread extends Thread{
private int ticket=10;
public void run(){
for(int i=0;i<20;i++){
if(this.ticket>0){
System.out.println(this.getName()+" 賣票:ticket"+this.ticket--);
}
}
}
};
public class ThreadTest {
public static void main(String[] args) {
// 啟動3個線程t1,t2,t3;每個線程各賣10張票!
MyThread t1=new MyThread();
MyThread t2=new MyThread();
MyThread t3=new MyThread();
t1.start();
t2.start();
t3.start();
}
}
運行結果:
Thread-0 賣票:ticket10
Thread-1 賣票:ticket10
Thread-2 賣票:ticket10
Thread-1 賣票:ticket9
Thread-0 賣票:ticket9
Thread-1 賣票:ticket8
Thread-2 賣票:ticket9
Thread-1 賣票:ticket7
Thread-0 賣票:ticket8
Thread-1 賣票:ticket6
Thread-2 賣票:ticket8
Thread-1 賣票:ticket5
Thread-0 賣票:ticket7
Thread-1 賣票:ticket4
Thread-2 賣票:ticket7
Thread-1 賣票:ticket3
Thread-0 賣票:ticket6
Thread-1 賣票:ticket2
Thread-2 賣票:ticket6
結果說明:
(01) MyThread繼承于Thread,它是自定義個線程。每個MyThread都會賣出10張票。
(02) 主線程main創建并啟動3個MyThread子線程。每個子線程都各自賣出了10張票。
2. Runnable的多線程示例
下面,我們對上面的程序進行修改。通過Runnable實現一個接口,從而實現多線程。
// RunnableTest.java 源碼
class MyThread implements Runnable{
private int ticket=10;
public void run(){
for(int i=0;i<20;i++){
if(this.ticket>0){
System.out.println(Thread.currentThread().getName()+" 賣票:ticket"+this.ticket--);
}
}
}
};
public class RunnableTest {
public static void main(String[] args) {
MyThread mt=new MyThread();
// 啟動3個線程t1,t2,t3(它們共用一個Runnable對象),這3個線程一共賣10張票!
Thread t1=new Thread(mt);
Thread t2=new Thread(mt);
Thread t3=new Thread(mt);
t1.start();
t2.start();
t3.start();
}
}
運行結果:
Thread-0 賣票:ticket10
Thread-2 賣票:ticket8
Thread-1 賣票:ticket9
Thread-2 賣票:ticket6
Thread-0 賣票:ticket7
Thread-2 賣票:ticket4
Thread-1 賣票:ticket5
Thread-2 賣票:ticket2
Thread-0 賣票:ticket3
Thread-1 賣票:ticket1
結果說明:
(01) 和上面“MyThread繼承于Thread”不同;這里的MyThread實現了Thread接口。
(02) 主線程main創建并啟動3個子線程,而且這3個子線程都是基于“mt這個Runnable對象”而創建的。運行結果是這3個子線程一共賣出了10張票。這說明它們是共享了MyThread接口的。