溫馨提示×

java中怎么通過thread類創建線程

小億
102
2023-11-22 22:13:48
欄目: 編程語言

在Java中,有兩種常見的方法可以通過Thread類創建線程。

第一種方法是繼承Thread類,重寫其run()方法。具體步驟如下:

  1. 創建一個繼承自Thread類的子類,并重寫run()方法。
public class MyThread extends Thread {
    @Override
    public void run() {
        // 線程執行的代碼
        System.out.println("Hello, World!");
    }
}
  1. 創建Thread子類的對象,并調用start()方法啟動線程。
public class Main {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
    }
}

第二種方法是實現Runnable接口,重寫其run()方法。具體步驟如下:

  1. 創建一個實現Runnable接口的類,并重寫run()方法。
public class MyRunnable implements Runnable {
    @Override
    public void run() {
        // 線程執行的代碼
        System.out.println("Hello, World!");
    }
}
  1. 創建Runnable實現類的對象。
public class Main {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
    }
}
  1. 創建Thread對象,將Runnable實現類的對象作為參數傳遞給Thread的構造方法。
public class Main {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();
    }
}

無論是繼承Thread類還是實現Runnable接口,線程的執行代碼都寫在run()方法中。調用start()方法會啟動線程,并自動調用run()方法。

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