java 核心編程——線程之線程的開發方法(二)

來源:互聯網
上載者:User

標籤:ble   time   休息   nts   font   xtend   抽象類別   col   一個   

1.繼承Thread類

  Thread類是一個具體的類,不是抽象類別。

package se.thread;import java.util.Date;public class ThreadTest extends  Thread {    public int time;    public String name;    ThreadTest(int time,String name){        this.name=name;        this.time=time;    }    public void run(){        while(true){            try {                System.out.println("使用者"+this.name+"正在休息,時間:"+new Date());                Thread.sleep(this.time);            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }    public static void main(String[] args) {        ThreadTest threadTest1 = new ThreadTest(100,"jack");        threadTest1.start();        ThreadTest threadTest2 = new ThreadTest(200,"lolo");        threadTest2.start();    }}

2.實現Runable介面

package se.thread;import java.util.Date;public class TreadTest2 implements Runnable {    public int time;    public String name;    public TreadTest2(int time,String name){        this.name=name;        this.time=time;    }    @Override    public void run() {        while(true){            try {                System.out.println("使用者"+this.name+"正在休息,時間:"+new Date());                Thread.sleep(this.time);            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }    public static void main(String[] args) {        TreadTest2 threadTest2 = new TreadTest2(3000,"004");        TreadTest2 treadTest22 = new TreadTest2(2000,"125");        new Thread(threadTest2).start();        new Thread(treadTest22).start();    }}

3.選擇Thread類還是Runable介面?

  1.如果只是想重寫Runable介面而不是重寫Thread其他方法,則使用Runable介面。

  2.如果子類繼承了其他非Thread類,則只能通過實現Runable介面來實現run()的重寫。

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.