Thread與Runnable區別
阿新 • • 發佈:2019-02-14
Thread和Runnable區別
執行多執行緒操作可以選擇- 繼承Thread類
- 實現Runnable介面
執行結果:package thread; public class ThreadTest { public static void main(String[] args) { MyThreadTest mt1 = new MyThreadTest("視窗1"); MyThreadTest mt2 = new MyThreadTest("視窗2"); MyThreadTest mt3 = new MyThreadTest("視窗3"); mt1.start(); mt2.start(); mt3.start(); } } class MyThreadTest extends Thread{ private int ticket = 5; private String name; public MyThreadTest(String name){ this.name = name; } public void run(){ while(true){ if(ticket < 1){ break; } System.out.println(name + " = " + ticket--); } } }
視窗1 = 5
視窗1 = 4
視窗1 = 3
視窗1 = 2
視窗1 = 1
視窗2 = 5
視窗3 = 5
視窗2 = 4
視窗3 = 4
視窗3 = 3
視窗3 = 2
視窗3 = 1
視窗2 = 3
視窗2 = 2
視窗2 = 1
結果一共賣出了5*3=15張票,這違背了"5張票"的初衷。造成此現象的原因就是:MyThreadTest mt1 = new MyThreadTest("視窗1"); MyThreadTest mt2 = new MyThreadTest("視窗2"); MyThreadTest mt3 = new MyThreadTest("視窗3"); mt1.start(); mt2.start(); mt3.start();
結果:package thread; public class RunnableTest { public static void main(String[] args) { MyRunnableTest mt = new MyRunnableTest(); Thread mt1 = new Thread(mt,"視窗1"); Thread mt2 = new Thread(mt,"視窗2"); Thread mt3 = new Thread(mt,"視窗3"); mt1.start(); mt2.start(); mt3.start(); } } class MyRunnableTest implements Runnable{ private int ticket = 5; public void run(){ while(true){ if(ticket < 1){ break; } System.out.println(Thread.currentThread().getName() + " = " + ticket--); } } }
視窗1 = 5
視窗1 = 2
視窗3 = 4
視窗2 = 3
視窗1 = 1
結果賣出了預期的5張票。原因在於: MyRunnableTest mt = new MyRunnableTest();
Thread mt1 = new Thread(mt,"視窗1");
Thread mt2 = new Thread(mt,"視窗2");
Thread mt3 = new Thread(mt,"視窗3");
mt1.start();
mt2.start();
mt3.start();
只建立了一個MyRunnableTest物件,而3個Thread執行緒都以同一個MyRunnableTest來啟動,所以他們的資源是共享的。