java多線程寫入同一文件

package com.thread;java

import java.io.File;多線程

import java.io.FileNotFoundException;ide

import java.io.FileOutputStream;測試

import java.io.IOException;ui

import java.util.concurrent.ConcurrentLinkedQueue;this

 * 多線程下寫文件spa

 * @author owen.huang線程

 * 將要寫入文件的數據存入隊列中orm

class Creater implements Runnable{隊列

 private ConcurrentLinkedQueue<String> queue;

 private String contents;

 public Creater(){}

 public Creater(ConcurrentLinkedQueue<String> 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<String> queue;

 public DealFile(){}

 public DealFile(FileOutputStream out,ConcurrentLinkedQueue<String> 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 {http://www.huiyi8.com/jiaoben/

    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<String> queue = new ConcurrentLinkedQueue<String>();

  for(int j=0;j<10;j++){

   new Thread(new Creater(queue,j+"--")).start();//多線程往隊列中寫入數據

  new Thread(new DealFile(out,queue)).start();//監聽線程,不斷從queue中讀數據寫入到文件中

相關文章
相關標籤/搜索