咱們在開發當中常常會使用到多線程,這裏咱們來寫兩個小案例經過最基本的兩種方式繼承Thread類或實現Runnable接口來實現一個多線程。java
咱們能夠經過繼承Thread類,並重寫run()方法的方式來建立一個線程,把線程中須要執行的內容放在run方法當中。多線程
public class ThreadOne extends Thread{ @Override public void run() { System.out.println("這是一個繼承Thread的多線程"); } }
或者咱們能夠經過繼承Runnable接口並實現接口中的run()方法的方式來實現一個線程,一樣線程中須要執行的內容放在run方法當中。ide
public class ThreadTwo implements Runnable{ public void run() { System.out.println("這是一個實現Runnable的多線程"); } }
上面僅僅是建立兩個線程,咱們還要使用線程,因此咱們要去調用這兩個線程,由於實現多線程的方式不一樣,因此這兩個線程的調用方式也有一些區別。this
繼承Thread的多線程調用方式很簡單,只用最普通的方式獲取實例便可調用,spa
下面有兩種方式獲取實現Runnable接口實例,不過兩種方式的實現原理基本相同。被註釋的方式爲分開寫的,即經過兩步獲取實例,第一步先經過Runnable接口獲取對應多線程類的實例,而後第二部將對應多線程實例放入到Thread類中。最後經過獲取的實例來調用start()方法啓動線程,這裏記住線程建立完畢後是不會啓動的,只有在調用完start()方法後纔會啓動。前先後後都繞不開Thread這個類,下面咱們就看看這個類的實現方式。線程
public class MyThread { public static void main(String[] args) { //繼承Thread類 ThreadOne threadOne = new ThreadOne(); //實現Runnable接口 Thread threadTwo = new Thread(new ThreadTwo()); //另外一種獲取實現Runnable接口類的多線程實例的方式 // Runnable runnable = new ThreadTwo(); // Thread threadTwo = new Thread(runnable); threadOne.start(); threadTwo.start(); } }
首先咱們打開Thread類會發現Thread類也實現了Runnable接口。code
public class Thread implements Runnable
根據上面兩種不一樣的方式調用啓動線程的方法咱們會發現,這兩個方法都是在調用Thread中的start()方法。具體的實現過程能夠看java源碼。繼承
public synchronized void start() { /** * This method is not invoked for the main method thread or "system" * group threads created/set up by the VM. Any new functionality added * to this method in the future may have to also be added to the VM. * * A zero status value corresponds to state "NEW". */ if (threadStatus != 0) throw new IllegalThreadStateException(); /* Notify the group that this thread is about to be started * so that it can be added to the group's list of threads * and the group's unstarted count can be decremented. */ group.add(this); boolean started = false; try { start0(); started = true; } finally { try { if (!started) { group.threadStartFailed(this); } } catch (Throwable ignore) { /* do nothing. If start0 threw a Throwable then it will be passed up the call stack */ } } }
因此java多線程歸根結底仍是根據Thread類和Runnable接口來實現的,Thread類也實現了Runnable接口並實現了接口中惟一的run方法。而且Thread把啓動線程的start方法定義在本身的類中,因此不管經過哪一種方式實現多線程最後都要調用Thread的start方法來啓動線程。這兩種方式建立多線程是爲了解決java不能多繼承的問題,若是某個想使用多線程的類已經擁有父類那麼能夠經過實現Runnable接口來實現多線程。接口