Java多線程完整版基礎知識__Java

來源:互聯網
上載者:User
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多線程例子

1 2 3 4 5 6 7 8 9 10 11

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.