Java基礎複習:線程建立

來源:互聯網
上載者:User

建立線程:

(1)方式1:繼承方式

/* * 建立線程的方式:繼承Thread類 * 1)建立一個類,繼承Thread * 2)覆寫run方法 * 3)建立一個線程對象 * 4)啟動線程(線程對象.start()) * */class MyThread extends Thread{public MyThread(String name){super(name);}@Overridepublic void run() {//線程體for(int i=0;i<100;i++){System.out.println(super.getName()+i);}}}public class ThreadDemo {public static void main(String[] args) {for (int i = 0; i < 200; i++) {String name = Thread.currentThread().getName();System.out.println(name+"---->"+i);if(i==50){new MyThread("well").start();}}}}

(2)方式2:實現方式

/* * 1. 定義一個類實現Runnable介面 * 2. 實現run方法 * 3. 線程對象的建立 new Thread(Runnable對象) * 4. 調用線程類的start方法 */class MyThread2 implements Runnable{@Overridepublic void run() {for (int i = 0; i < 100; i++) {String name = Thread.currentThread().getName();System.out.println(name+"---->"+i);}}}public class ThreadDemo2 {public static void main(String[] args) {for (int i = 0; i < args.length; i++) {System.out.println("main-->"+i);if(i==10){new Thread(new MyThread2(),"hello").start();}}}}

currentThread()  返回對當前正在執行的線程對象的引用

getName()  擷取線程名稱

setName() 設定線程名稱

聯繫我們

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