在Java中,可以通過(guò)繼承Thread類(lèi)或?qū)崿F(xiàn)Runnable接口來(lái)創(chuàng)建多線程。下面分別介紹兩種方法:
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();
}
}
以上是兩種最常見(jiàn)的創(chuàng)建多線程的方式,可以根據(jù)具體需求選擇合適的方法。