用Java多线程怎么写
时间: 2023-06-30 14:03:09 浏览: 50
在Java中使用多线程需要创建Thread类的实例,并重写run()方法,run()方法中包含了多线程执行的逻辑。下面是一个简单的Java多线程示例:
```java
public class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
```
在这个示例中,我们创建了一个继承自Thread类的MyThread类,并重写了run()方法。在main()方法中,我们创建了一个MyThread类的实例,并调用了它的start()方法,这样就启动了一个新的线程。
除了继承Thread类,还可以实现Runnable接口来创建多线程。下面是一个实现Runnable接口的Java多线程示例:
```java
public class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running");
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
```
在这个示例中,我们创建了一个实现了Runnable接口的MyRunnable类,并实现了run()方法。在main()方法中,我们创建了一个Thread类的实例,并传入了MyRunnable类的实例,这样就启动了一个新的线程。
无论是继承Thread类还是实现Runnable接口,都需要重写run()方法并在其中编写多线程执行的逻辑。同时,start()方法才是启动线程的正确方式,直接调用run()方法是不会启动新线程的。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)