溫馨提示×

java怎么實現(xiàn)多線程并發(fā)執(zhí)行

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

Java實現(xiàn)多線程并發(fā)執(zhí)行的方式有兩種:繼承Thread類和實現(xiàn)Runnable接口。

  1. 繼承Thread類:

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

    • 定義一個類,實現(xiàn)Runnable接口,重寫run()方法,在run()方法中寫入線程執(zhí)行的邏輯。
    • 創(chuàng)建線程對象,將實現(xiàn)了Runnable接口的對象作為參數(shù)傳入Thread類的構造方法中,調(diào)用start()方法啟動線程。
    • 例子:
    public class MyRunnable implements Runnable {
        @Override
        public void run() {
            // 線程執(zhí)行的邏輯
        }
    }
    
    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();
        }
    }
    

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

0