Java程序开启多线程
时间: 2023-07-06 11:34:39 浏览: 55
Java程序开启多线程可以使用Thread类或者实现Runnable接口来创建线程。
1. 继承Thread类
创建一个继承Thread类的子类,并重写run()方法,run()方法中是线程要执行的任务。创建线程对象后,调用start()方法启动线程。
示例代码:
```java
class MyThread extends Thread {
public void run() {
// 线程要执行的任务
System.out.println("MyThread is running");
}
}
public class Test {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start(); // 启动线程
}
}
```
2. 实现Runnable接口
创建一个实现Runnable接口的类,并实现其中的run()方法,run()方法中是线程要执行的任务。创建线程对象后,将Runnable对象作为参数传递给Thread类的构造函数,然后调用start()方法启动线程。
示例代码:
```java
class MyRunnable implements Runnable {
public void run() {
// 线程要执行的任务
System.out.println("MyRunnable is running");
}
}
public class Test {
public static void main(String[] args) {
MyRunnable r = new MyRunnable();
Thread t = new Thread(r); // 将MyRunnable对象传递给Thread类的构造函数
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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)