* 按流向获取文件
* @param order
* @return
* @throws Exception
*/
public String schedule(int order) throws Exception{
String file;
lock.lock();
try {
//如果初次进入的非1线程 则等待 又1线程开始获取 并唤醒下一线程
while (!turn[order]) {
condition[order].await();
}
file = flow.getFileInFlow();
Thread.sleep(100);
turn[order] = false;//自身等待
order = order == 3 0 : order + 1;
turn[order] = true;//唤醒下一位
condition[order].signal();
} finally {
lock.unlock();
}
return file;
}
/**
* 写入文件
* @param order
* @param file
* @param Content
* @throws Exception
*/
public void write(int order,String file,String Content)throws Exception{
synchronized (FileScheduler.class) {
if (!isVisiting.containsKey(file)) {
isVisiting.put(file, false);
outputMap.put(file,new StringBuffer(file+":"));
}
}
synchronized (FileScheduler.class) {
while ((Boolean) isVisiting.get(file)) {
Integer lockObj = (Integer)lockObjMap.get(order);//号卡
synchronized (lockObj) {
System.out.println("线程" + (order+1) + "等待" + file);
lockObj.wait();
}
}
}
//并发写入
isVisiting.put(file, true);
System.out.println("线程" + (order+1) + "开始写文件" + file + "..");
Thread.sleep(new Random().nextInt(4)*1000);
System.out.println("线程" + (order+1) + "写文件" + file + "结束..");
System.out.println(sb.append(Content).toString());
isVisiting.put(file, false);
//如果存在等待线程 则通过号卡唤醒
Integer nextLockObj = (Integer)lockObjMap.get(order == 3 0 : order + 1);
synchronized (nextLockObj) {
nextLockObj.notify();
}
}
}
/**
* 文件类 按照某个流向供应文件对象
* @author zengjf
*
*/
class FileFlow{
private ArrayList
private BlockingQueue
private String[] filenames = {"A","B","C","D"};
public FileFlow(int nums){
for (int i = 0; i < nums && i< filenames.length; i++) {
list.add(filenames[i]);
}
ExecutorService es = Executors.newSingleThreadExecutor();
es.execute(new Runnable(){
public void run() {
while(true){
int i ;
for ( i = 0; i < list.size(); i++) {
try {
queue.put(list.get(i));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.add(0,list.remove(i-1));
}
}
});
}
public String getFileInFlow(){
try {
return queue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
public int length(){
return list.size();
}
}
摘自 Goodspeed85