進程與線程的概念。
進程:是操作系統為一個程序分配內存空間的基本單位。
線程:存在于一個進程里,是程序執行的基本單元。線程才是負責是去執行程序的。
java創建線程的方式:
一:繼承Thread類,java為我們提供了封裝好的線程類 Thread
class MyThread extends Thread{ @Override public void run() { System.out.PRintln("WTF?"); }}并且 new MyThread().start();這樣JVM就會起開啟一個線程,然后去執行run()方法里面的代碼。 注意只有是run方里面的代碼才是線程執行的,并且得有JVM去調用,自己調用run方法不起租用。必須得調用start。二:實現Runnable接口。
class MyRunnable implements Runnable{ public void run() { }}扔給Thread類并調用start方法 new Thread(new MyRunnable()).start();切記,一定是扔給Thread的類,并且調用了start方法才會去開啟一個線程并且執行run方法代碼。
那么繼承Thread類和實現Runnable接口方法有什么區別?
第一:java是單繼承的,如果一個類繼承了Thread類,那么這個類不能再繼承任何類,我們知道什么時候才需要繼承,在開發中,往往是有邏輯上和數據上的共同時才需要繼承,而如果僅僅是要執行多線程的話就把繼承這唯一的機會給使用了,那么后面的局限性太大了,所以java又提供了實現Runnable接口這一方式。
第二:其實Thread類是實現了Runnable接口的類,從接口和類上來分析這件事,不難理解,接口只是定義一個協議,就是run方法,java與我們協議,要在多線程中執行的代碼放在run方法中,所以這就是Runnable接口的由來,那么到底該如何開啟線程呢? 這就是Thread類,java實現了自己的Runnable接口并且封裝了這個功能類,就叫Thread類。
所以在java中要想開啟一個線程,必須是調用了Thread或者它子類的start方法,而run方法只是保存要在多線程中執行的代碼的一個接口方法。
而且Thread類的run方法源碼是這樣的:
@Override public void run() { if (target != null) { target.run(); } }而這個target就是Runnable對象。并且Thread類的start方法源碼是這樣的:
/** * Causes this thread to begin execution; the Java Virtual Machine * calls the <code>run</code> method of this thread. //中文注釋: 調用此方法這個線程就是開啟是執行,JVM會調用線程的run方法。 * <p> * The result is that two threads are running concurrently: the * current thread (which returns from the call to the * <code>start</code> method) and the other thread (which executes its * <code>run</code> method). //中文注釋:結果是當前有兩個線程在運行,一個是此線程,另一個是開啟此線程的線程 * <p> * It is never legal to start a thread more than once. * In particular, a thread may not be restarted once it has completed * execution. //中文注釋:它從不會被啟動多次,一個線程不可能在它還沒完成之前被啟動多次 * (注意,一個線程在沒執行完之前如果被啟動,會拋出非法狀態異常) * @exception IllegalThreadStateException if the thread was already * started. * @see #run() * @see #stop() */ public synchronized void start() { //...此方法的解釋被我刪除 group.add(this); boolean started = false; try { start0(); started = true; } finally { .... } } //本地方法,去調用該操作系統開啟一個線程 private native void start0();
新聞熱點
疑難解答