JAVA學習筆記(三十七)- 建立繼承Thread的線程

來源:互聯網
上載者:User

標籤:thread   線程建立   

建立繼承Thread的線程
/* * 建立線程方式一:繼承自Thread * 步驟: * 1.自訂類,繼承自Thread類 * 2.重寫run()方法 * 3.建立類的執行個體,即建立一個線程 * 4.調用線程的start()方法,作用:啟動線程、調用run()方法 *  *  * Thread的run方法,用於儲存線程要執行的代碼,必須重寫此方法 * 啟動線程時會自動調用此方法 */class Demo extends Thread{    @Override    public void run() {        for(int i=1;i<=50;i++){            System.out.println("*****run*******"+i);        }    }}public class Test01 {    public static void main(String[] args) {        Demo demo=new Demo();//建立一個線程        demo.start();//啟動線程並執行該線程的run方法        //demo.run();僅僅是調用對象的方法,線程雖然建立了,但並未啟動        for(int i=1;i<=50;i++){            System.out.println("*****Hello World*******"+i);        }    }}
建立兩個線程
/* *  建立兩個線程 * * 線程預設名稱 * 自訂線程:Thread-編號,從0開始 * 主線程:main *  * 查看線程名稱 * getName() * Thread.currentThread() 擷取當前線程執行個體 *  * 設定線程名稱 * 通過構造方法、 *  */class MyThread extends Thread {    public MyThread(String name){        super(name);    }    @Override    public void run() {        System.out.println(Thread.currentThread()==this);        for (int i = 1; i <= 50; i++) {            //System.out.println(getName()+"*****run*******" + i);            System.out.println(Thread.currentThread().getName()+"*****run*******" + i);        }    }}public class Test02 {    public static void main(String[] args) {        // 建立兩個線程並啟動        MyThread t1 = new MyThread("線程一");        MyThread t2 = new MyThread("線程二");        t1.setName("first");        t1.start();        t2.start();        Thread thread=Thread.currentThread();//擷取當前線程執行個體        for (int i = 1; i <= 50; i++) {            System.out.println(thread.getName()+"*****Hello World*******" + i);        }    }}

JAVA學習筆記(三十七)- 建立繼承Thread的線程

聯繫我們

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