在Java中,有两种常见的方法来创建多线程:
class MyThread extends Thread {
public void run() {
// 线程要执行的任务
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 启动线程
}
}
class MyRunnable implements Runnable {
public void run() {
// 线程要执行的任务
}
}
public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start(); // 启动线程
}
}
这两种方法都可以实现多线程,但通常推荐使用实现Runnable接口的方式,因为Java只支持单继承,通过实现接口的方式可以避免类继承的限制。此外,实现Runnable接口的方式还可以更好地实现代码的解耦和复用。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:java多线程创建方法是什么