java多进程编程代码实现
时间: 2023-10-11 08:25:03 浏览: 45
以下是Java多进程编程的代码示例,包括使用ProcessBuilder启动新进程和使用线程池并发执行任务:
1. 使用ProcessBuilder启动新进程:
```java
import java.io.IOException;
public class ProcessBuilderExample {
public static void main(String[] args) {
ProcessBuilder builder = new ProcessBuilder("notepad.exe", "test.txt");
try {
builder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
2. 使用线程池并发执行任务:
```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable task = new Task(i);
executor.execute(task);
}
executor.shutdown();
}
private static class Task implements Runnable {
private int taskId;
public Task(int id) {
this.taskId = id;
}
@Override
public void run() {
System.out.println("Task #" + this.taskId + " is running.");
}
}
}
```
上述代码会创建一个包含5个线程的线程池,然后启动10个任务并发执行。每个任务输出一条消息,表示任务正在运行。
相关推荐
![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)