针对一道笔试题线程+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();
}
}
}
- 针对一道笔试题线程+io流的练笔
- 金山的一道有关线程的笔试题
- java线程 --- 一道迅雷笔试题 (一)
- Cisco的一道笔试题
- 思科的一道笔试题
- 一道有趣的笔试题
- 华为的一道笔试题
- 一道简单的笔试题
- 一道经典的笔试题
- 广联达的一道笔试题
- ThoughtWorks 的一道笔试题
- NokiaSimens的一道笔试题
- 淘宝笔试的一道题
- 网易笔试的一道题
- 一道Intel的笔试题
- 一道有趣的笔试题
- 华为的一道笔试题
- 阿里巴巴的一道笔试题
- 鼠标事件的距离
- Android SDK以及
- Unite Europe案例项目《影子战术》层级优化经验分享
- NZT安装教程
- Android 资源文件命名规范
- 针对一道笔试题线程+io流的练笔
- js 通过传入 开始时间和结束时间 算出相差多少秒 分钟 相差时间
- 转载 make版MYsql 5.5.13
- 自动装箱与自动拆箱
- Java学习笔记-多态性
- CSDN修改资源分数值,取消0分,最低分为1分
- Junit的使用实例
- CentOS7利用pip快速安装TensorFlow
- VS VC 编译调试比特币源码