如何缩小同步范围
来源:9-3 Spring与线程安全
目科将
2018-08-02
接上一个问题(http://coding.imooc.com/learn/questiondetail/71817.html), 我的测试代码及现象如下:
public static void main(String[] args) {
ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("doing-%d").build();
ThreadPoolExecutor executor = new ThreadPoolExecutor(100, 100, 0L, TimeUnit.MINUTES,
new LinkedBlockingQueue<Runnable>(1), threadFactory, new ThreadPoolExecutor.AbortPolicy());
final FileService fileService = new FileService();
for (int i = 0; i < 100; i++) {
executor.execute(new Runnable() {
@Override
public void run() {
fileService.write("20180802");
}
});
}
executor.shutdown();
}
public static class FileService {
private static final String TEST_DIR = "/test4mut";
private static final String FLAG = "/_DOING";
public void write(String date){
if(check(date)){
System.out.println(Thread.currentThread().getName() + " doing....");
}else{
//System.out.println("---------");
}
}
public boolean check(String date){
String dir = TEST_DIR+date;
File flag = new File(dir+FLAG);
if(flag.exists()){
return false;
}else{
try {
flag.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
} 运行结果:
doing-0 doing.... doing-1 doing....
想问下老师,我上面那个同步应该怎么编写
写回答
1回答
-
你好,我先说一下我的理解,你现在是起多个线程去创建同一个文件是吧,然后这样很可能在 flag.createNewFile();时抛出异常,你问的是这种情况下如何避免对吧,如果是的话,你可以对
if(flag.exists()){
return false;
}else{
try {
flag.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
这段代码加上同步手段。主要是保证 flag.exists() 和 flag.createNewFile(); 两个操作的原子性。
032018-08-03
相似问题