runnable和thread
时间: 2024-06-18 09:04:20 浏览: 4
在Java中,线程可以通过继承Thread类或实现Runnable接口来创建。Runnable接口为关联Thread对象的线程提供执行的代码。这些代码放在Runnable的void run()方法中,这个方法虽然不接受任何参数且没有返回值,但是有可能抛出异常。具体来说,Thread类就是实现了Runnable接口,Thread类中的run()方法也是对Runnable接口中的run()方法的实现。我们可以通过以下两种方式来创建Thread和Runnable对象:
1.继承Thread类。我们需要重写Thread类的run()方法,然后在该方法中编写线程的业务逻辑。最后我们可以实例化Thread类对象,并调用其start()方法来启动线程。例如:
```java
class MyThread extends Thread {
public void run() {
System.out.println("MyThread is running!");
}
}
```
2.实现Runnable接口。我们需要重写接口的run()方法,然后在该方法中编写线程的业务逻辑。最后,我们可以将Runnable实例传递给Thread类的构造函数来实例化Thread对象。例如:
```java
class MyRunnable implements Runnable {
public void run() {
System.out.println("MyRunnable is running!");
}
}
```
然后我们可以这样来启动一个线程:
```java
MyThread mt = new MyThread();
mt.start();
MyRunnable mr = new MyRunnable();
Thread t = new Thread(mr);
t.start();
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)