Java 建立一个多线程程序,分别用两个线程读取x1,x2两个文件数据内容,数字部分乘以2倍,间隔两秒中往X3文件中复制写入一次数据
时间: 2024-09-12 07:16:18 浏览: 52
在Java中创建一个多线程程序,你可以使用`Thread`类或者更推荐的`ExecutorService`和`Callable`/`Future`来实现。这里是一个简单的示例,我们将使用`java.util.concurrent`包下的工具:
```java
import java.io.*;
import java.util.concurrent.*;
public class MultiThreadedFileProcessor {
private static final String FILE_X1 = "x1.txt";
private static final String FILE_X2 = "x2.txt";
private static final String FILE_X3 = "x3.txt";
public static void main(String[] args) throws IOException, InterruptedException {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future1 = executor.submit(new FileReaderAndWriter(FILE_X1, FILE_X3, 2000));
Future<String> future2 = executor.submit(new FileReaderAndWriter(FILE_X2, FILE_X3, 2000));
// 等待所有任务完成并关闭线程池
try {
String result1 = future1.get(); // 获取第一个文件处理结果
String result2 = future2.get(); // 获取第二个文件处理结果
System.out.println("Results: " + result1 + ", " + result2);
} catch (ExecutionException e) {
e.printStackTrace();
} finally {
executor.shutdown();
}
}
// 文件读取并乘以2后写入新文件的线程类
private static class FileReaderAndWriter implements Callable<String> {
private String inputFile;
private String outputFile;
private long interval;
public FileReaderAndWriter(String inputFile, String outputFile, long interval) {
this.inputFile = inputFile;
this.outputFile = outputFile;
this.interval = interval;
}
@Override
public String call() {
try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
String line;
while ((line = reader.readLine()) != null) {
int number = Integer.parseInt(line); // 假设都是整数
int doubledNumber = number * 2;
writer.write(doubledNumber + "\n"); // 写入新的数值
Thread.sleep(interval); // 暂停两秒
}
return "Write to file " + outputFile + " completed.";
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
```
在这个例子中,我们创建了一个单线程的`ExecutorService`,然后提交了两个任务(`future1`和`future2`),每个任务代表读取一个文件并每两秒写入到`FILE_X3`。注意,实际应用中需要处理可能出现的异常,并在适当的时候关闭输入输出流。
阅读全文