java線程的實現

來源:互聯網
上載者:User

java線程的實現
1.進程與線程    進程是程式的一次動態執行過程,它經曆了從代碼載入、執行到執行完畢的一個完整過程。    多進程作業系統能同時運行多個進程(程式),由於CPU具備分時機制,所以每個進程都能迴圈獲得自己的CPU時間片。由於CPU執行速度非常快,使得所有程式好像在"同時"運行。    線程是在進程基礎上的進行進一步劃分。多線程是指一個進程在執行過程中可以產生多個線程,這些線程可以同時存在、同時運行。    多線程機制可以同時運行多個程式塊,當有線程包含耗時操作(如迴圈),可以讓另一個線程做其他的處理。傳統程式語言一次只能運行一個程式塊,遇到耗時操作只能按順序執行完耗操作才能繼續執行程式。    2.java中線程的實現①繼承Thread類文法 class 類名稱 extends Thread {    //繼承Thread類    屬性...;                //類中定義屬性    方法...;                 //類中定義方法    public void run() {        //覆寫Thread類中的run()方法,此方法是線程的主體        //線程主體    }}樣本:ThreadDemo.java   class MyThread extends Thread {    private String name;     public MyThread(String name) {        this.name = name;    }     public void run() {        for (int i = 0; i < 10; i++) {            System.out.println(name + "運行,i= " + i);        }    }} public class ThreadDemo {    public static void main(String[] args) {        // TODO Auto-generated method stub        MyThread mt1 = new MyThread("線程A");        MyThread mt2 = new MyThread("線程A");        mt1.start();        mt2.start();    } }    註:使用start()方法啟動多線程而不用run()方法啟動線程的原因。    start()方法調用start0()方法,start0()方法使用native關鍵字聲明,說明啟動多線程的實現需要依靠底層作業系統支援。    繼承Thread類實現多線程,同一線程類對象只能調用一次start()方法,調用多次會出拋出IllegaIlThreadStateException異常。源碼: 

 public synchronized void start() {        /**         * This method is not invoked for the main method thread or "system"         * group threads created/set up by the VM. Any new functionality added         * to this method in the future may have to also be added to the VM.         *         * A zero status value corresponds to state "NEW".         */        if (threadStatus != 0)            throw new IllegalThreadStateException();        /* Notify the group that this thread is about to be started         * so that it can be added to the group's list of threads         * and the group's unstarted count can be decremented. */        group.add(this);        boolean started = false;        try {            start0();            started = true;        } finally {            try {                if (!started) {                    group.threadStartFailed(this);                }            } catch (Throwable ignore) {                /* do nothing. If start0 threw a Throwable then                  it will be passed up the call stack */            }        }    }

 

     private native void start0();     ②實現Runnable介面文法:     class 類名稱 implements Runnable{    //實現Runnable介面    屬性...;                //類中定義屬性    方法...;                 //類中定義方法    public void run() {        //覆寫Runnable介面中的run()方法        //線程主體    }}樣本:
RunnableDemo.java class MyThread01 extends Thread {    private String name;    public MyThread01(String name) {        this.name = name;    }    public void run() {        for (int i = 0; i < 10; i++) {            System.out.println(name + "運行,i= " + i);        }    }}public class RunnableDemo {    public static void main(String[] args) {        // TODO Auto-generated method stub        MyThread mt1 = new MyThread("線程A");        MyThread mt2 = new MyThread("線程A");        Thread t1 = new Thread(mt1);        Thread t2 = new Thread(mt2);        t1.start();        t2.start();    }}

 

    啟動線程需要Thread類中的start()方法,Thread類中的run()方法調用的是Runnable介面中的run()方法,此方法由Runnable子類完成,所以如果通過繼承Thread類實現多線程,則必須覆寫run()方法。    Thread類中的建構函式接受Runnable的子類,所以可以通過Thread類來啟動該線程。源碼: 
private Runnable target;public Thread(Runnable target,String name){    init(null,target,name,0);}...public void run(){    if(target != null){        target.run();    }}

 

     使用Runnable介面實現多線程可以避免由於java的單繼承帶來的局限。注: 1.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.