把项目中一个大文件对比进行了简单了模拟,多线程将大文件下的多个文件分割,lock控制差异同步写入到一个list中;当所有线程执行完毕,read 所有内容。
package cn.com.ld.study.thread;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* @filename: LockTest
* @description: TODO
* @author java 小生
* @date 2013-2-18 下午6:07:34
*/
public class LockTest {
Lock rlock = new ReentrantReadWriteLock().writeLock();
Lock lock = new ReentrantLock();// 锁
private Collection<String> strc = new ArrayList<String>();
private int readSequence;
private int writeTimes = 0;
LockTest(int writeTimes) {
this.writeTimes = writeTimes;
}
public boolean write(String name) {
try {
lock.lock();
readSequence++;
System.out.println(name + " 被" + readSequence + "次写入");
strc.add(name + readSequence);
} finally {
lock.unlock();
}
return writeTimes == readSequence ? true : false;
}
public void read() {
System.out.println("读取写入内容开始.....");
for (Iterator<String> iterator = strc.iterator(); iterator.hasNext();) {
String type = (String) iterator.next();
System.out.println(type+" 被输出。。。。");
}
System.out.println("读取写入内容结束.....");
}
public static void main(String[] args) throws InterruptedException {
final LockTest lockTest = new LockTest(100);
List<Future<Boolean>> fList = new ArrayList<Future<Boolean>>();
Callable<Boolean> write = new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return lockTest.write("张三");
}
};
ExecutorService cachedService = Executors.newCachedThreadPool();
Future<Boolean> future = null;
for (int i = 0; i < 100; i++) {
future = cachedService.submit(write);
fList.add(future);
}
while (true) {
int writeLent = lockTest.strc.size() ;
if (writeLent == 100 && fList.get(99).isDone()) {
lockTest.read() ;
break ;
}
}
}
}