溫馨提示×

java怎么創建子線程

小億
96
2023-11-04 11:34:06
欄目: 編程語言

Java中創建子線程可以有兩種方式:

  1. 繼承Thread類并重寫run()方法:
public class MyThread extends Thread {
    @Override
    public void run() {
        // 子線程的具體邏輯
    }
}

public static void main(String[] args) {
    MyThread myThread = new MyThread();
    myThread.start(); // 啟動子線程
}
  1. 實現Runnable接口并實現run()方法:
public class MyRunnable implements Runnable {
    @Override
    public void run() {
        // 子線程的具體邏輯
    }
}

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

無論使用哪種方式,都需要調用start()方法來啟動子線程。

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