在Java中实现多线程有两种方法:
- 继承Thread类:定义一个类继承Thread类,并重写run()方法,在run()方法中编写线程的任务逻辑。然后创建该类的实例并调用start()方法启动线程。
public class MyThread extends Thread { public void run() { // 线程任务逻辑 } } public class Main { public static void main(String[] args) { MyThread myThread = new MyThread(); myThread.start(); } }
- 实现Runnable接口:定义一个类实现Runnable接口,并实现run()方法,在run()方法中编写线程的任务逻辑。然后创建该类的实例并将其传递给Thread类的构造方法,然后调用start()方法启动线程。
public 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(); } }
以上两种方法都可以实现多线程,但一般来说推荐使用第二种方法,因为Java是单继承的,如果继承了Thread类就无法再继承其他类了,而实现Runnable接口可以避免这个问题。