Java 多線程 (Thread 類)

來源:互聯網
上載者:User

標籤:lap   介面   spl   int   實現   啟動   out   對象   pen   

 1.多線程  

 

1.多線程實現

兩種方式可以實現多線程:

  • 繼承 Thread 類,重寫 run 方法;定義對象,調用 start 方法
  • 建立類實現 Runnable 介面,作為實參傳遞給 thread 的構造方法。定義對象,調用 start 方法。
1.1.繼承 Thread
  • 繼承類,重寫方法
class TDemo1 extends Thread {    public String name; // 取個名字,便於識別        public TDemo1 (String name) { // 構造方法        this.name = name;    }    @Override    public void run() { // 重寫  run 方法        show();    }    public void show() {        System.out.println(name + ": talk show time");    }}
View Code
  • 建立對象,調用 start 方法啟動線程
TDemo1 td1 = new TDemo1("梁宏達");TDemo1 td2 = new TDemo1("李晨偉");TDemo1 td3 = new TDemo1("竇文濤");TDemo1 td4 = new TDemo1("備胎說車");td1.start();td2.start();td3.start();td4.start();
View Code

 

1.2.實現 Runnable
  •  實現介面
class TDemo2 implements Runnable {    public String name; // 識別        public TDemo2(String name) { // 構造方法        this.name = name;    }    @Override    public void run() { // 實現方法        show();    }    private void show() {        System.out.println(name + " 新媒體開播");    }    } 
View Code
  • 建立對象,調用方法 start
Thread td1 = new Thread(new TDemo2("備胎說車"));Thread td2 = new Thread(new TDemo2("30秒懂車"));Thread td3 = new Thread(new TDemo2("汽車洋蔥圈"));Thread td4 = new Thread(new TDemo2("根叔說車"));        td1.start();td2.start();td3.start();td4.start();
View Code

 

 

 

 

 

 

 

 

 

a

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.