共計 700 個字符,預計需要花費 2 分鐘才能閱讀完成。
Java 中多線程的使用方法有兩種:一種是通過繼承 Thread 類來創建線程,另一種是通過實現 Runnable 接口來創建線程。
- 通過繼承 Thread 類來創建線程:
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();}
}
- 通過實現 Runnable 接口來創建線程:
class MyRunnable implements Runnable {@Override
public void run() {// 線程執行的代碼
}
}
public class Main {public static void main(String[] args) {MyRunnable myRunnable = new MyRunnable();
Thread thread1 = new Thread(myRunnable);
Thread thread2 = new Thread(myRunnable);
thread1.start();
thread2.start();}
}
這兩種方法都可以用來創建多個線程,并且在 start() 方法調用后,線程會異步執行。在實際應用中,一般推薦使用實現 Runnable 接口的方式來創建線程,因為 Java 不支持多重繼承,而通過實現 Runnable 接口可以避免這個限制。
丸趣 TV 網 – 提供最優質的資源集合!
正文完