java多线程读写文件示例
package com.ysh.file;
import java.util.arraylist;
import java.util.linkedlist;
import java.util.list;
import java.util.concurrent.locks.condition;
import java.util.concurrent.locks.lock;
import java.util.concurrent.locks.reentrantlock;
import com.google.common.collect.lists;
public class writequeue {
private static final int max_queue_size = 10000;
private linkedlist<string> queuecache = lists.newlinkedlist();
private lock lock = new reentrantlock();
private condition full = lock.newcondition();
private condition empty = lock.newcondition();
private writequeue() {
}
private static class writequeueholder {
private final static writequeue instance = new writequeue();
}
public static writequeue getinstance() {
return writequeueholder.instance;
}
public void add(string line) {
lock.lock();
try {
while (queuecache.size() >= max_queue_size) {
full.await();
}
queuecache.addfirst(line);
empty.signal();
} catch (interruptedexception e) {
e.printstacktrace();
} finally {
lock.unlock();
}
}
public void add(list<string> linelist) {
lock.lock();
try {
while (queuecache.size() >= max_queue_size) {
full.await();
}
queuecache.addall(linelist);
empty.signal();
} catch (interruptedexception e) {
e.printstacktrace();
} finally {
lock.unlock();
}
}
public arraylist<string> flush() {
arraylist<string> temp = null;
lock.lock();
try {
while (queuecache.size() == 0) {
empty.await();
}
temp = lists.newarraylist();
temp.addall(queuecache);
queuecache.clear();
full.signal();
} catch (interruptedexception e) {
e.printstacktrace();
} finally {
lock.unlock();
}
return temp;
}
}
上一篇: MySQL 从一张表update字段到另外一张表中
下一篇: MySQL日志维护策略汇总