Java基礎學習總結,java基礎總結

來源:互聯網
上載者:User

Java基礎學習總結,java基礎總結

 

  多線程的實現方法:

    繼承Thread類

    實現Runnable類

  -------------------------------------------------------------------------------------

  1. 繼承Thread類

    繼承Thread類之後,需要覆蓋父類的 public void run() 方法,作為線程的主方法。

    所有線程的執行一定是並發的,即:同一個時間段上會有多個線程交替執行。為了達到這樣的目的,絕對不能直接調用run()方法,而是應該調用Thread類的start()方法啟動多線程。

    調用 start() 方法和調用 run() 方法的對比:

public class MyThread extends Thread {    private String name;    public MyThread(String name) {        this.name = name;    }        @Override    public void run() {        for(int i=0; i<10; i++) {        System.out.println(name + "列印:" + i);        }    }        public static void main(String[] args) {        MyThread mt1 = new MyThread("線程A");        MyThread mt2 = new MyThread("線程B");        MyThread mt3 = new MyThread("線程C");        mt1.start();        mt2.start();        mt3.start();    }}

  運行結果:(三個線程同時且交替執行,沒有固定的執行順序)

   

public class MyThread extends Thread {    private String name;    public MyThread(String name) {        this.name = name;    }        @Override    public void run() {        for(int i=0; i<5; i++) {        System.out.println(name + "列印:" + i);        }    }        public static void main(String[] args) {        MyThread mt1 = new MyThread("線程A");        MyThread mt2 = new MyThread("線程B");        MyThread mt3 = new MyThread("線程C");        mt1.run();        mt2.run();        mt3.run();    }}

  運行結果:(三個程式依次順序執行)

   

  2. start()方法實現多線程的原理

    開啟Thread類原始碼中start()方法的部分:

public synchronized void start() {        if (threadStatus != 0)            throw new IllegalThreadStateException();        group.add(this);        boolean started = false;        try {            start0();            started = true;        } finally {            try {                if (!started) {                    group.threadStartFailed(this);                }            } catch (Throwable ignore) {            }        }}private native void start0();

    native關鍵字是指叫用作業系統的方法,start0()方法是所在作業系統的方法。

    由於線程的啟動需要牽扯到作業系統中資源的分配問題,所以具體的線程的啟動應該根據不同的作業系統有不同的實現。而JVM根據不同的作業系統中定義的start0()方法進行不同的實現。這樣,在多線程的層次上start0()方法的名稱不改變,而不同的作業系統有不同的實現。

原理圖

    結論:只有Thread類的start()方法才能進行作業系統資源的分配,所以啟動多線程的方式永遠就是Thread類的start()方法。

聯繫我們

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