溫馨提示×

java怎么實現多線程并發執行

小億
127
2023-10-24 21:10:52
欄目: 編程語言

Java實現多線程并發執行的方式有兩種:繼承Thread類和實現Runnable接口。

  1. 繼承Thread類:

    • 定義一個類,繼承Thread類,重寫run()方法,在run()方法中寫入線程執行的邏輯。
    • 創建線程對象,調用start()方法啟動線程。
    • 例子:
    public class MyThread extends Thread {
        @Override
        public void run() {
            // 線程執行的邏輯
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            MyThread thread1 = new MyThread();
            MyThread thread2 = new MyThread();
            thread1.start();
            thread2.start();
        }
    }
    
  2. 實現Runnable接口:

    • 定義一個類,實現Runnable接口,重寫run()方法,在run()方法中寫入線程執行的邏輯。
    • 創建線程對象,將實現了Runnable接口的對象作為參數傳入Thread類的構造方法中,調用start()方法啟動線程。
    • 例子:
    public class MyRunnable implements Runnable {
        @Override
        public void run() {
            // 線程執行的邏輯
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            MyRunnable runnable1 = new MyRunnable();
            MyRunnable runnable2 = new MyRunnable();
            Thread thread1 = new Thread(runnable1);
            Thread thread2 = new Thread(runnable2);
            thread1.start();
            thread2.start();
        }
    }
    

這兩種方式都可以實現多線程并發執行,但是實現Runnable接口的方式更常用,因為Java只支持單繼承,如果已經繼承了其他類,就無法再繼承Thread類,而實現Runnable接口不會有這個問題。此外,使用Runnable接口還可以實現線程的資源共享,多個線程可以共享同一個Runnable對象的資源,實現更靈活的線程操作。

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