此處僅簡單介紹同一任務多線程並行執行時的資源共享,不介紹多線程數據同步。多線程
public class ShareResource extends Thread{ private static int index = 1; private static final int MAX = 50; @Override public void run(){ while(index <= MAX){ System.out.println(index++); } } public static void main(String args[]) { Thread thread1 = new ShareResource(); Thread thread2 = new ShareResource(); thread1.start(); thread2.start(); } }
當建立 ShareThread 的多個實例,並並行執行時,能夠經過使用 static 關鍵字修改類的成員,便可達到多線程下共享資源的惟一性的目的。可是 static 修飾的變量的生命週期很長,若是須要共享的資源不少,共享資源要通過一些比較複雜的計算,此種方式就再也不適用。ide
建立線程只有一種方式——構造 Thread 類。 實現線程的執行單元有兩種方方式:線程
public class ShareResourceWithImplRunnable implements Runnable{ private int index = 1; private final int MAX = 1000; @Override public void run(){ while(index <= MAX){ System.out.println(index++); } } public static void main(String[] args) { ShareResourceWithImplRunnable shareResourceWithImplRunnable = new ShareResourceWithImplRunnable(); Thread thread1 = new Thread(shareResourceWithImplRunnable); Thread thread2 = new Thread(shareResourceWithImplRunnable); thread1.start(); thread2.start(); } }
如上所示,ShareResourceWithImplRunnable 類實現了 Runnable 接口,建立一個 ShareResourceWithImplRunnable 類的實例,將 ShareResourceWithImplRunnable 的實例用於構造 多個 Thread,當多個並行運行時,一樣能夠達到多個線程之間共享資源的目的。code
Thread 中有一個 Runnable 的接口變量:對象
private Runnable target;
使用 Runnable 的實現類的實例做爲構造 Thread 對象的實參時,target 將會引用這個 Runnable 接口的實例對象。當調用 Thread 線程 start 方法以後,在線程執行時,會調用 Thread 的 run 方法。在 Thread 的run 方法中調用 target.run() 方法,即 調用 Runnable 接口實現類的實例對象的 run 方法。以下爲 Thread run 方法的實現:繼承
@Override public void run() { if (target != null) { target.run(); } }