今天收到了同学的一个笔试题,内容如下:
4个线程 线程1 打印A 线程2打印B 线程3打印C 线程4打印D
向文件1中写入ABCDABCDABCD...
向文件2写入BCDABCDA...
向文件3写入CDABCDAB...
向文件4写入DABCDABC...
试着写了一下:
package zmine.threadmore;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
public class TestSleep {
static int[] fileDeepth = {0,0,0,0}; //代表4个文件的深度
static String[] filepaths = {"d:\\txt1.txt","d:\\txt2.txt","d:\\txt3.txt","d:\\txt4.txt"};
public static void main(String[] args){
int count = 10; //打印次数
new ThreadA(count).start();
new ThreadB(count).start();
new ThreadC(count).start();
new ThreadD(count).start();
}
private static class ThreadA extends Thread{
private int count ;
public ThreadA(int count){
this.count=count;
}
public void run(){
int printAcount = 1;
for(int i=0;i<count;i++){
while(fileDeepth[printAcount-1] != i){
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("begin A print ... " + System.currentTimeMillis());
BufferedWriter opt = null ;
try{
opt = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filepaths[printAcount-1],true)));
opt.write("A");
System.out.println("第"+(i+1)+"次打印A,打印输出在第"+printAcount+"个文件");
}catch(Exception e){
e.printStackTrace();
}finally{
if(opt != null){try{opt.close();}catch(Exception e){}}
}
fileDeepth[printAcount-1] = i+1; //深度加1
printAcount--;
if(printAcount == 0){
printAcount =4 ;
}
}
}
}
private static class ThreadB extends Thread{
private int count ;
public ThreadB(int count){
this.count=count;
}
public void run(){
int printBcount = 2;
for(int i=0;i<count;i++){
while(fileDeepth[printBcount-1] != i){
try {
Thread.sleep(5);
}