java多线程写文件

 
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

可以看出线程的先后执行是随机的

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值