java开启三个线程,其他线程的run方法是做写入以线程名命名的文件
时间: 2023-12-29 13:22:11 浏览: 26
以下是一个示例代码,用于开启三个线程并在其他线程的 run 方法中进行文件写入操作:
```java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class ThreadExample {
public static void main(String[] args) {
Thread thread1 = new WriteToFileThread("Thread-1");
Thread thread2 = new WriteToFileThread("Thread-2");
Thread thread3 = new WriteToFileThread("Thread-3");
thread1.start();
thread2.start();
thread3.start();
}
}
class WriteToFileThread extends Thread {
private String threadName;
public WriteToFileThread(String name) {
threadName = name;
}
public void run() {
String fileName = threadName + ".txt";
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
writer.write("This is written by " + threadName);
System.out.println("File " + fileName + " written by " + threadName);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
该代码首先创建一个 WriteToFileThread 类,用于在 run 方法中进行文件写入操作。每个线程都会创建一个以其名字命名的文件,并写入一条信息。然后在 main 方法中创建三个 WriteToFileThread 对象并启动它们的线程。三个线程会同时运行,各自写入对应的文件。
注意:在实际开发中,需要注意文件命名的唯一性,以免出现重名的情况导致文件被覆盖。
相关推荐
![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)