java创建多线程同时执行不同任务
时间: 2023-08-04 11:25:28 浏览: 55
在Java中,创建多线程同时执行不同任务可以使用以下两种方法:
1. 实现Runnable接口
通过实现Runnable接口来创建线程,需要实现run()方法,该方法中定义了线程要执行的任务。然后创建一个Thread对象,将实现了Runnable接口的类的对象作为参数传入,最后调用start()方法启动线程。
示例代码:
```
class MyRunnable implements Runnable {
public void run() {
// 线程要执行的任务
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread1 = new Thread(myRunnable);
Thread thread2 = new Thread(myRunnable);
thread1.start();
thread2.start();
}
}
```
上述代码中,创建了两个线程thread1和thread2,它们都执行MyRunnable类中定义的任务。
2. 继承Thread类
通过继承Thread类来创建线程,需要重写run()方法,该方法中定义了线程要执行的任务。然后创建一个Thread类的子类的对象,调用start()方法启动线程。
示例代码:
```
class MyThread extends Thread {
public void run() {
// 线程要执行的任务
}
}
public class Main {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start();
thread2.start();
}
}
```
上述代码中,创建了两个线程thread1和thread2,它们都执行MyThread类中定义的任务。
无论是哪种方法,都可以创建多个线程同时执行不同任务。
相关推荐
![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)