在Java中,有两种方法可以创建多线程:
- 继承
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(); } }
- 实现
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()
方法。