Java多線程:“基礎篇”02之常用的實現多線程的兩種方式

來源:互聯網
上載者:User

本章,我們學習“常用的實現多線程的2種方式”:Thread 和 Runnable。

之所以說是常用的,是因為通過還可以通過java.util.concurrent包中的線程池來實現多線程。關於線程池的內容,我們以後會詳細介紹;現在,先對的Thread和Runnable進行瞭解。本章內容包括:

Thread和Runnable的簡介

Thread和Runnable的異同點

Thread和Runnable的多線程的樣本

轉載請註明出處:http://www.cnblogs.com/skywang12345/p/3479063.html

Thread和Runnable簡介

Runnable 是一個介面,該介面中只包含了一個run()方法。它的定義如下:

public interface Runnable {

   public abstract void run();

}

Runnable的作用,實現多線程。我們可以定義一個類A實現Runnable介面;然後,通過new Thread(new A())等方式建立線程。

Thread 是一個類。Thread本身就實現了Runnable介面。它的聲明如下:

public class Thread implements Runnable {}

Thread的作用,實現多線程。

Thread和Runnable的異同點

Thread 和 Runnable 的相同點:都是“多線程的實現方式”。

Thread 和 Runnable 的不同點:

Thread 是類,而Runnable是介面;Thread本身是實現了Runnable介面的類。我們知道“一個類只能有一個父類,但是卻能實現多個介面”,因此Runnable具有更好的擴充性。

此外,Runnable還可以用於“資源的共用”。即,多個線程都是基於某一個Runnable對象建立的,它們會共用Runnable對象上的資源。

通常,建議通過“Runnable”實現多線程!

Thread和Runnable的多線程樣本

1. Thread的多線程樣本

下面通過樣本更好的理解Thread和Runnable,借鑒網上一個例子比較具有說服性的例子。

// ThreadTest.java 源碼class MyThread extends Thread{      private int ticket=10;      public void run(){        for(int i=0;i<20;i++){             if(this.ticket>0){                System.out.println(this.getName()+" 賣票:ticket"+this.ticket--);            }        }    } };    public class ThreadTest {      public static void main(String[] args) {          // 啟動3個線程t1,t2,t3;每個線程各賣10張票!        MyThread t1=new MyThread();        MyThread t2=new MyThread();        MyThread t3=new MyThread();        t1.start();        t2.start();        t3.start();    }  }

運行結果:

Thread-0 賣票:ticket10Thread-1 賣票:ticket10Thread-2 賣票:ticket10Thread-1 賣票:ticket9Thread-0 賣票:ticket9Thread-1 賣票:ticket8Thread-2 賣票:ticket9Thread-1 賣票:ticket7Thread-0 賣票:ticket8Thread-1 賣票:ticket6Thread-2 賣票:ticket8Thread-1 賣票:ticket5Thread-0 賣票:ticket7Thread-1 賣票:ticket4Thread-2 賣票:ticket7Thread-1 賣票:ticket3Thread-0 賣票:ticket6Thread-1 賣票:ticket2Thread-2 賣票:ticket6Thread-2 賣票:ticket5Thread-2 賣票:ticket4Thread-1 賣票:ticket1Thread-0 賣票:ticket5Thread-2 賣票:ticket3Thread-0 賣票:ticket4Thread-2 賣票:ticket2Thread-0 賣票:ticket3Thread-2 賣票:ticket1Thread-0 賣票:ticket2Thread-0 賣票:ticket1

聯繫我們

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