Java多線程完整版基礎知識 (翟開順由厚到薄系列) 1.前言
線程是現代作業系統中一個很重要的概念,多線程功能很強大,java語言對線程提供了很好的支援,我們可以使用java提供的thread類很容易的建立多個線程。線程很不難,我對之前學習過的基礎,在這做了一個整理,本文主要參考的是Java研究組織出版的j2se進階和張孝祥-java就業培訓教材這兩本書 2.概述 2.1線程是什麼
主要是線程與進程的區別,這裡不再闡述,自行網上搜尋
為什麼使用線程:作業系統切換多個線程要比調度進程在速度上快很多,進程間無法共用,通訊麻煩。線程之間由於共用資料,所以交換資料很方便
下面有個例子去解釋多線程與單線程
A單線程例子
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package firstTread; /** * @author zhaikaishun * */ public class TreadDemo1 { public static void main(String[] args) { new TestThread().run(); //會一直執行這段代碼 while(true){ System.out.println("main thread is running"); } } } class TestThread{ //這裡沒有繼承Thread類 public void run(){ while (true){ System.out.println("TestThread is here run");//會一直執行 } } } |
運行後出現
TestThread is here run
TestThread is here run
TestThread is here run
TestThread is here run
TestThread is here run
...
分析:這裡是單線程,會按照順序,只會執行TestThread類的方法
B多線程例子