溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Thread與runnable在java中有什么不同

發布時間:2020-12-02 16:27:05 來源:億速云 閱讀:185 作者:Leah 欄目:編程語言

Thread與runnable在java中有什么不同 ?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。

java中實現多線程的方法有兩種:繼承Thread類和實現runnable接口

1,繼承Thread類,重寫父類run()方法

  public class thread1 extends Thread {
 
    public void run() {
        for (int i = 0; i < 10000; i++) {
            System.out.println("我是線程"+this.getId());
        }
    }
 
    public static void main(String[] args) {
        thread1 th2 = new thread1();
        thread1 th3 = new thread1();
        th2.run();
        th3.run();
    }
   } 

run()方法只是普通的方法,是順序執行的,即th2.run()執行完成后才執行th3.run(),這樣寫只用一個主線程。多線程就失去了意義,所以應該用start()方法來啟動線程,start()方法會自動調用run()方法。上述代碼改為:

 public class thread1 extends Thread {
    
    public void run() {
        for (int i = 0; i < 10000; i++) {
            System.out.println("我是線程"+this.getId());
        }
    }
 
    public static void main(String[] args) {
        thread1 th2 = new thread1();
        thread1 th3 = new thread1();
        th2.start();
        th3.start();
    }
}

通過start()方法啟動一個新的線程。這樣不管th2.start()調用的run()方法是否執行完,都繼續執行th3.start()如果下面有別的代碼也同樣不需要等待th3.start()執行完成,而繼續執行。(輸出的線程id是無規則交替輸出的) 

2,實現runnable接口

public class thread2 implements Runnable {
 
    public String ThreadName;
    
    public thread2(String tName){
        ThreadName = tName;
    }
    
    
    public void run() {
        for (int i = 0; i < 10000; i++) {
            System.out.println(ThreadName);
        }
    }
    
    public static void main(String[] args) {
        thread2 th2 = new thread2("線程A");
        thread2 th3 = new thread2("Thread-B");
        th2.run();
        th3.run();
    }
}

和Thread的run方法一樣Runnable的run只是普通方法,在main方法中th3.run()必須等待th2.run()執行完成后才能執行,程序只用一個線程。要多線程的目的,也要通過Thread的start()方法(runnable是沒有start方法)。上述代碼修改為:

public class thread2 implements Runnable {
 
    public String ThreadName;
    
    public thread2(String tName){
        ThreadName = tName;
    }
    
    
    public void run() {
        for (int i = 0; i < 10000; i++) {
            System.out.println(ThreadName);
        }
    }
    
    public static void main(String[] args) {
        thread2 th2 = new thread2("線程A");
        thread2 th3 = new thread2("Thread-B");
        Thread myth2 = new Thread(th2);
        Thread myth3 = new Thread(th3);
        myth2.start();
        myth3.start();
    }
}

 總結:實現java多線程的2種方式,runable是接口,thread是類,runnable只提供一個run方法,建議使用runable實現 java多線程,不管如何,最終都需要通過thread.start()來使線程處于可運行狀態。

看完上述內容,你們掌握Thread與runnable在java中有什么不同 的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女