溫馨提示×

Java怎么實現多線程

小億
104
2023-11-13 10:47:28
欄目: 編程語言

Java可以通過實現Thread類或者實現Runnable接口來實現多線程。

  1. 繼承Thread類:
public class MyThread extends Thread {
    public void run() {
        // 該方法中的代碼會在創建線程后被執行
        System.out.println("線程執行了");
    }

    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start(); // 啟動線程
    }
}
  1. 實現Runnable接口:
public class MyRunnable implements Runnable {
    public void run() {
        // 該方法中的代碼會在創建線程后被執行
        System.out.println("線程執行了");
    }

    public static void main(String[] args) {
        Thread thread = new Thread(new MyRunnable());
        thread.start(); // 啟動線程
    }
}

以上兩種方式都是創建線程,區別在于繼承Thread類要直接實現run方法,而實現Runnable接口要通過傳入Runnable對象來創建Thread對象,并在Runnable對象中實現run方法。

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