Chinaunix首页 | 论坛 | 博客
  • 博客访问: 79913
  • 博文数量: 98
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 600
  • 用 户 组: 普通用户
  • 注册时间: 2014-06-10 21:50
文章分类
文章存档

2014年(98)

我的朋友

分类: Java

2014-07-19 11:30:54

package com.thread;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.ConcurrentLinkedQueue;
 * 多线程下写文件
 * @author owen.huang
 * 将要写入文件的数据存入队列中
class Creater implements Runnable{
 private ConcurrentLinkedQueue queue;
 private String contents;
 public Creater(){}
 public Creater(ConcurrentLinkedQueue queue, String contents){
  this.queue = queue;
  this.contents = contents;
 public void run() {
  try {
   Thread.sleep(100); 
  } catch (InterruptedException e) {
   e.printStackTrace();
  queue.add(contents);
 * 将队列中的数据写入到文件
class DealFile implements Runnable{
 private FileOutputStream out;
 private ConcurrentLinkedQueue queue;
 public DealFile(){}
 public DealFile(FileOutputStream out,ConcurrentLinkedQueue queue){
  this.out = out;
  this.queue = queue;
 public void run() {
  while(true){//循环监听
   if(!queue.isEmpty()){ 
    try {
     out.write(queue.poll().getBytes());
    } catch (IOException e) {
     e.printStackTrace();
   try {
    Thread.sleep(100);
   } catch (InterruptedException e) {
    e.printStackTrace();*
 * 测试类
public class TestMultipleWriteFile {
 public static void main(String[] args) throws FileNotFoundException{
  FileOutputStream out = new FileOutputStream(new File("F:"+ File.separator +"test.txt"),true);
  ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue();
  for(int j=0;j<10;j++){
   new Thread(new Creater(queue,j+"--")).start();//多线程往队列中写入数据
  new Thread(new DealFile(out,queue)).start();//监听线程,不断从queue中读数据写入到文件中
阅读(2276) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~