1. 程式人生 > 實用技巧 >Runnable與Thread區別

Runnable與Thread區別

簡述

Runnable是介面,Thread是類且實現Runnable介面

Thread執行緒是獨立的不共享資源

Runnable是資源共享

在使用Runnable定義的子類中沒有start()方法,只有Thread類中才有。

Thread類,有一個構造方法:public Thread(Runnable targer)

此構造方法接受Runnable的子類例項,也就是說可以通過Thread類來啟動Runnable實現的多執行緒。

public Thread(Runnable runnable)  
{  
    daemon = false;  
    stillborn = false;  
    threadLocals = null;  
    inheritableThreadLocals = null;  
    threadStatus = 0;  
    blockerLock = new Object();  
    init(null, runnable, (new StringBuilder()).append("Thread-").append(nextThreadNum()).toString(), 0L);  
}  

  

使用情況

在程式開發中只要是多執行緒肯定永遠以實現Runnable介面為主。

實現Runnable介面相比繼承Thread類有如下好處:
1、避免繼承的侷限,一個類可以繼承多個介面。
2、適合於資源的共享。

舉例

三個網友分別搶10張優惠券

繼承Thread

/**
 * MyThreadWithExtends
 * 
 * @author Stephen
 * @time 2020-7-1 17:59:02
 */
public class MyThreadWithExtends extends Thread {

	private int number = 10;

	@Override
	public void run() {

		for (int i = 0; i <= 100; i++) {
			if (number > 0) {
				number--;//優惠卷減一
				System.out.println(Thread.currentThread().getName() + "顧客搶到手,剩餘優惠券:" + number);
			}
		}
	}

	public static void main(String[] args) {
		MyThreadWithExtends thread1 = new MyThreadWithExtends();
		MyThreadWithExtends thread2 = new MyThreadWithExtends();
		MyThreadWithExtends thread3 = new MyThreadWithExtends();

		thread1.start();
		thread2.start();
		thread3.start();

		// 每個執行緒都獨立,不共享資源,每個執行緒都搶了10張,總共搶了30張。如果真搶,就有問題了。
	}

}

 

執行結果

/**
 * MyThreadWithExtends
 * 
 * @author Stephen
 * @time 2020-7-1 17:59:59
 */
public class MyThreadWithExtends  implements Runnable {

	private int number = 10;

	@Override
	public void run() {

		for (int i = 0; i <= 100; i++) {
			if (number > 0) {
				number--;//優惠卷減一
				System.out.println(Thread.currentThread().getName() + "顧客搶到手,剩餘優惠券:" + number);
			}
		}
	}

	public static void main(String[] args) {
		MyThreadWithExtends myClass = new MyThreadWithExtends();
		Thread thread1 = new Thread(myClass,"網友1");
		Thread thread2 = new Thread(myClass,"網友2");
		Thread thread3 = new Thread(myClass,"網友3");

		thread1.start();
		thread2.start();
		thread3.start();
	}

}