温馨提示×

java怎么创建多线程

小亿
108
2023-08-12 04:50:30
栏目: 编程语言

在Java中,有两种方法可以创建多线程:

  1. 继承Thread类:创建一个类,继承自Thread类,并重写run()方法,将线程执行的代码放在run()方法中。然后创建该类的实例,调用start()方法启动线程。
public class MyThread extends Thread {
public void run() {
// 线程执行的代码
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
  1. 实现Runnable接口:创建一个类,实现Runnable接口,并重写run()方法,将线程执行的代码放在run()方法中。然后创建该类的实例,作为参数传递给Thread类的构造函数,调用start()方法启动线程。
public class MyRunnable implements Runnable {
public void run() {
// 线程执行的代码
}
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}

无论是继承Thread类还是实现Runnable接口,都需要将线程执行的代码放在run()方法中。start()方法会启动线程,并自动调用run()方法。

0