Java中调用多线程的方法有两种:
示例代码:
class MyThread extends Thread {
public void run() {
// 线程执行的任务
}
}
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}
示例代码:
class MyRunnable implements Runnable {
public void run() {
// 线程执行的任务
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
这两种方法都可以实现多线程的调用,但推荐使用实现Runnable接口的方式,因为Java是单继承的,如果已经继承了其他类,就无法再继承Thread类,此时可以通过实现Runnable接口来创建线程。此外,实现Runnable接口还可以使代码更加清晰和可扩展。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:java多线程并发调用接口的方法是什么