Java基礎——多線程

來源:互聯網
上載者:User

標籤:rgs   完成   sub   img   對象   分享   log   oid   類對象   

 

 

package test;//建立線程的第一種方式:繼承java.lang.Thread類//1.建立一個繼承Thread的子類class SubThread extends Thread {//2.重寫run()方法,方法內實現此子線程要完成的任務public void run() {for(int i = 0; i < 100; ++i) {System.out.println(Thread.currentThread().getName() + ": " + i);}}}public class TestThread {public static void main(String[] args) {//3.建立一個子類的對象SubThread st = new SubThread();//4.調用線程的start()方法:啟動此線程;並且調用相應的run()方法//一個線程只能執行一次start();//不能通過直接調用Thread實作類別對象的run()方法去啟動一個線程 st.run();//錯誤的,相當於主線程內啟動的st.start();for(int i = 0; i < 100; ++i) {System.out.println(Thread.currentThread().getName() + ": " + i);}}}

  

 

package test;//1.建立一個實現了Runnable介面的類class SubThread1 implements Runnable{//2.實現介面的抽象方法public void run() {//子線程執行的代碼for(int i = 0; i < 50; ++i) {System.out.println(Thread.currentThread().getName() + ": " + i);}}}public class TestThread1 {public static void main(String[] args) {//3.建立一個Runnable介面實作類別的對象SubThread1 p = new SubThread1();//要想啟動多線程,必須調用start()//4.將此方法作為形參傳遞給Thread類的構造器中,建立Thread類的對象,此對象即為一個線程Thread t1 = new Thread(p);//5.調用start()方法,啟動線程並執行run()t1.start();//再建立一個線程Thread t2 = new Thread(p); //不用再重新建立p,直接傳入Thread即可t2.start();}}

  

 

 

 

Java基礎——多線程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.