一.先看兩段代碼
通過繼承Thread類
class MyThread extends Thread{ private int ticket = 10; private String name; public MyThread(String name){ this.name =name; } public void run(){ for(int i =0;i<500;i++){ if(this.ticket>0){ System.out.println(this.name+"賣票---->"+(this.ticket--)); } } } } public class ThreadDemo { public static void main(String[] args) { MyThread mt1= new MyThread("一號視窗"); MyThread mt2= new MyThread("二號視窗"); MyThread mt3= new MyThread("三號視窗"); mt1.start(); mt2.start(); mt3.start(); } } 運行結果:
一號視窗賣票---->10 一號視窗賣票---->9 二號視窗賣票---->10 一號視窗賣票---->8 一號視窗賣票---->7 一號視窗賣票---->6 三號視窗賣票---->10 一號視窗賣票---->5 一號視窗賣票---->4 一號視窗賣票---->3 一號視窗賣票---->2 一號視窗賣票---->1 二號視窗賣票---->9 二號視窗賣票---->8 三號視窗賣票---->9 三號視窗賣票---->8 三號視窗賣票---->7 三號視窗賣票---->6 三號視窗賣票---->5 三號視窗賣票---->4 三號視窗賣票---->3 三號視窗賣票---->2 三號視窗賣票---->1 二號視窗賣票---->7 二號視窗賣票---->6 二號視窗賣票---->5 二號視窗賣票---->4 二號視窗賣票---->3 二號視窗賣票---->2 二號視窗賣票---->1
通過實現Runnable介面
class MyThread1 implements Runnable{ private int ticket =10; private String name; public void run(){ for(int i =0;i<500;i++){ if(this.ticket>0){ System.out.println(Thread.currentThread().getName()+"賣票---->"+(this.ticket--)); } } } } public class RunnableDemo { public static void main(String[] args) { // TODO Auto-generated method stub //設計三個線程 MyThread1 mt = new MyThread1(); Thread t1 = new Thread(mt,"一號視窗"); Thread t2 = new Thread(mt,"二號視窗"); Thread t3 = new Thread(mt,"三號視窗"); t1.start(); t2.start(); t3.start(); } }
運行結果:
一號視窗賣票---->10 三號視窗賣票---->9 三號視窗賣票---->7 三號視窗賣票---->5 三號視窗賣票---->4 三號視窗賣票---->3 三號視窗賣票---->2 三號視窗賣票---->1 一號視窗賣票---->8 二號視窗賣票---->6
造成上面的差異的就是,繼承Runnable介面的時候,new了一個 Thread1 ,然後通過三個線程來共用一個Thread1 ,這樣三個進程就共用了資源int ticket =10;
MyThread1 mt1 = new MyThread1(); MyThread1 mt2 = new MyThread1(); MyThread1 mt2 = new MyThread1(); Thread t1 = new Thread(mt1,"一號視窗"); Thread t2 = new Thread(mt2,"二號視窗"); Thread t3 = new Thread(mt3,"三號視窗");
這樣的話, 就跟繼承Thread類的結果是一樣的了
總結一下,,實現Runable除了避免單繼承的局限外,還有個好處就是能實現不同進程資源共用,而繼承Thread沒有這個功能。並不是這個特點是兩者的絕對區別,繼承Runable你可以選擇不共用。