package cn.uestc.fz;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class FileWriteThread {
public static void main(String[] args) {
FThread f1 = new FThread();
FThread f2 = new FThread();
Thread t1 = new Thread(f1, "thread1");
Thread t2 = new Thread(f2, "thread2");
Thread t3 = new Thread(f2, "thread3");
Thread t4 = new Thread(f2, "thread4");
Thread t5 = new Thread(f2, "thread5");
Thread t6 = new Thread(f2, "thread6");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
}
}
class FThread implements Runnable {
File file = new File("e://a.txt");
BufferedWriter bw;
public FThread() {
try {
bw = new BufferedWriter(new FileWriter(file, true));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void run() {
try {
bw.write(Thread.currentThread().getName() + ":aaaaaaaaa");
bw.newLine();
bw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
运行3次结果 打开E:/a.txt文件
thread1:aaaaaaaaa
thread3:aaaaaaaaa
thread2:aaaaaaaaa
thread5:aaaaaaaaa
thread4:aaaaaaaaa
thread6:aaaaaaaaa
thread1:aaaaaaaaa
thread3:aaaaaaaaa
thread5:aaaaaaaaa
thread2:aaaaaaaaa
thread4:aaaaaaaaa
thread6:aaaaaaaaa
thread1:aaaaaaaaa
thread3:aaaaaaaaa
thread2:aaaaaaaaa
thread4:aaaaaaaaa
thread5:aaaaaaaaa
thread6:aaaaaaaaa
可以看出线程的先后执行是随机的