在Java中,有两种主要的方式来创建多线程:
1.继承Thread类:创建一个新的类并继承Thread类,然后重写run()方法来定义线程执行的任务。最后,创建该类的实例并调用start()方法启动线程。
public class MyThread extends Thread {
public void run() {
// 线程执行的任务
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
2.实现Runnable接口:创建一个实现了Runnable接口的类,实现run()方法来定义线程执行的任务。然后,创建一个Thread对象,将实现了Runnable接口的类作为参数传递给Thread对象,并调用start()方法启动线程。
public class MyRunnable implements Runnable {
public void run() {
// 线程执行的任务
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}