在Java中,可以通過繼承Thread類或實現Runnable接口來創建多線程。下面分別介紹兩種方法:
public class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
public class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running");
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
以上是兩種最常見的創建多線程的方式,可以根據具體需求選擇合適的方法。