首先 Thread是類,Runable是接口。
一是寫一個類繼承自Thread類,然後重寫裏面的run方法,用start方法啓動線程
二是寫一個類實現Runnable接口,實現裏面的run方法,用new Thread(Runnable target).start()方法來啓動
查看源碼可以發現 Thread也是實現的Runable
public class Thread implements Runnable {
兩個都可以實現多線程編程,但是基於java是單繼承,所以實現Runable更靈活。並且Runable可以簡單的實現變量的線程間共享。
繼承Thread
static class MyThread1 extends Thread{ private int ticket=10; private String threadName; public MyThread1( String threadName) { this.threadName = threadName; } @Override public void run() { for(;ticket>0;ticket--){ System.out.println(threadName+"賣出火車票號:"+ticket); } } }
public static void main(String[] args){ MyThread1 thread1=new MyThread1("從線程1"); MyThread1 thread2=new MyThread1("從線程2"); thread1.start(); thread2.start(); // MyThread2 thread3=new MyThread2("Runable實現類"); // new Thread(thread3).start(); // new Thread(thread3).start(); }
執行結果:
實現Runable 實現共享
static class MyThread2 implements Runnable{ private int ticket=10; private String threadName; public MyThread2( String threadName) { this.threadName = threadName; } @Override public void run() { for(;ticket>0;ticket--){ System.out.println(threadName+"賣出火車票號:"+ticket); } } }
public static void main(String[] args) { // MyThread1 thread1=new MyThread1("從線程1"); // MyThread1 thread2=new MyThread1("從線程2"); // thread1.start(); // thread2.start(); MyThread2 thread3 = new MyThread2("Runable實現類"); new Thread(thread3).start(); new Thread(thread3).start(); }執行結果:
雖然這樣可以共享但是這樣也存在數據不同步的現象:
兩個線程可能讀到的ticket不是同步的;
這就需要在實現類里加入同步的代碼:
{ synchronized (this){ for (; ticket > 0; ticket--) { System.out.println(threadName + "賣出火車票號:" + ticket); } } }