针对一道笔试题线程+io流的练笔

来源:互联网 发布:seo工程师 编辑:程序博客网 时间:2024/06/05 18:51

昨天去面试,做到一道关于线程+io流的基本代码题,感觉基础知识结合的挺好的,介于第一次写博客,没有那么多经验,就从最简单的知识代码开始写。

题目是这样的:编写4个线程分别完成创建F1.txt,F2.txt,F3.txt,F4.txt的文件,并分别重复4次写入"ABCD","BCDA","CDBA","DABC"到各自对应的文件中。

废话不多说,直接代码了

线程类

package thread;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

@SuppressWarnings("all")
public class FileRunable implements Runnable {

private String pathname;

private String context;


public FileRunable(String pathname, String context) {
this.pathname = pathname;
this.context = context;
}

//活用线程和io流读写
public void run() {
File file=new File(pathname);
try {
BufferedWriter out=new BufferedWriter(new FileWriter(file));
for(int i=0;i<4;i++){
//System.out.println(i);
out.write(context);
}
//out.flush();
//每次读写完毕要把流关闭,不然并不会写入
            out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

测试类

package thread;

public class ThreadTest {

//活用线程和io流读写
public static void main(String[] args) {
Thread thread1=new Thread(new FileRunable("E:\\F1.txt","ABCD"));
thread1.start();
Thread thread2=new Thread(new FileRunable("E:\\F2.txt","BCDA"));
thread2.start();
Thread thread3=new Thread(new FileRunable("E:\\F3.txt","CDAB"));
thread3.start();
Thread thread4=new Thread(new FileRunable("E:\\F4.txt","DABC"));
thread4.start();
try {

//只是为了保证主线程在子线程完成后才结束
thread1.join();
thread2.join();
thread3.join();
thread4.join();

//查看子线程的存货状态
System.out.println(thread1.isAlive());
System.out.println(thread2.isAlive());
System.out.println(thread3.isAlive());
System.out.println(thread4.isAlive());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

原创粉丝点击