java实现多线程的两种方法
时间: 2023-07-26 15:15:55 浏览: 53
在Java中,实现多线程的两种方法分别是:
1. 继承Thread类
继承Thread类是Java中实现多线程的一种方式。实现多线程的关键是重写Thread类中的run()方法,run()方法中放置线程需要执行的代码。然后通过创建Thread类的实例,调用其start()方法启动线程。
示例代码如下:
```
public class MyThread extends Thread {
public void run() {
// 线程需要执行的代码
}
}
// 启动线程
MyThread thread = new MyThread();
thread.start();
```
2. 实现Runnable接口
实现Runnable接口也是Java中实现多线程的一种方式。实现多线程的关键是实现Runnable接口中的run()方法,run()方法中放置线程需要执行的代码。然后通过创建Thread类的实例,将实现了Runnable接口的类的实例作为参数传入,调用Thread类的start()方法启动线程。
示例代码如下:
```
public class MyRunnable implements Runnable {
public void run() {
// 线程需要执行的代码
}
}
// 启动线程
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
```
这两种方法都可以实现多线程,但是实现Runnable接口的方式相比继承Thread类的方式更为灵活,因为它可以避免单继承的限制,同时还可以实现资源共享。因此,在实际开发中,实现Runnable接口的方式更为常用。