首页 技术 正文
技术 2022年11月11日
0 收藏 431 点赞 4,972 浏览 1599 个字

Java并发之CyclicBarria的使用(二)

一.简介

  之前借助于其他大神写过一篇关于CyclicBarria用法的博文,但是内心总是感觉丝丝的愧疚,因为笔者喜欢原创,而不喜欢去转载一些其他的文章,为此笔者自己原创了一个CyclicBarria的用法的示例Demo, 在此声明,该Demo没有实际的价值,仅仅只是演示CyclicBarria的用法,希望加深读者对”循环栅栏”的用法加深理解。

二.使用

  需求假设:在D盘下有一个test文件夹,我们要使用两个线程将文件夹A, B, 拷贝到test目录下,必须要等到两个文件夹都拷贝完毕,然后再将其删除。

public class CyclicBarriaTest {    static class ProcessDir extends Thread{        private CyclicBarrier cb;        private CountDownLatch cdl;        private String path;        private int num;        public ProcessDir(String path, CyclicBarrier cb, int num, CountDownLatch cdl){
this.num = num;
this.cb = cb;
this.path = path;
this.cdl = cdl;
} @Override
public void run() {
try {
cb.await();
copyDir();
cb.await();
deleteDir();
} catch (Exception e) {
e.printStackTrace();
}finally{
cdl.countDown();
}
} /**
* 拷贝文件夹
* @throws IOException
*/
public void copyDir() throws IOException{
if(num == 1){
FileUtils.copyDirectory(new File("D:/eclipse"), new File(path));
} if(num == 2){
FileUtils.copyDirectory(new File("D:/maven"), new File(path));
}
} /**
* 删除文件夹
* @throws IOException
*/
public void deleteDir() throws IOException{
if(num == 1){
FileUtils.deleteDirectory(new File("d:/test/eclipse"));
} if(num == 2){
FileUtils.deleteDirectory(new File("d:/test/maven"));
}
}
} static class ShowInfo implements Runnable{ private boolean flag; public ShowInfo(boolean flag){
this.flag = flag;
} @Override
public void run() {
if(flag){
System.out.println("所有的线程已经 准备完毕,开始执行拷贝");
flag = false;
}else{
System.out.println("数据拷贝完毕,开始执行删除");
}
}
} public static void main(String[] args) throws InterruptedException {
CyclicBarrier cb = new CyclicBarrier(2, new ShowInfo(true));
CountDownLatch cdl = new CountDownLatch(2); for(int i = 1; i <= 2; i++){
new ProcessDir("d:/test", cb, i, cdl).start();
} cdl.await(); File file = new File("d:/test");
file.delete();
}
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,085
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,560
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,409
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,182
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,819
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,902