在Java中,創建一個新線程有兩種主要方法:
下面是兩種方法的示例:
方法1:繼承Thread類
class MyThread extends Thread {
public void run() {
// 在這里編寫你的代碼
System.out.println("線程正在運行...");
}
}
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start(); // 啟動新線程
}
}
方法2:實現Runnable接口
class MyRunnable implements Runnable {
public void run() {
// 在這里編寫你的代碼
System.out.println("線程正在運行...");
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable); // 創建新線程
thread.start(); // 啟動新線程
}
}
這兩種方法都可以創建一個新線程并啟動它。你可以根據自己的需求選擇合適的方法。