多線程往文件裏寫數據

在此輸入圖片描述package com.test.DB;java

import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.concurrent.ConcurrentLinkedQueue;this

class Creater implements Runnable {code

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 {ip

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 {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

}get

public class TestMultipleWriteFile {it

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();
}

}io

相關文章
相關標籤/搜索