• 多线程辅助类之CyclicBarrier(四)


    CyclicBarrier是一个线程辅助类,和《多线程辅助类之CountDownLatch(三)》功能类似,都可以实现一组线程的相互等待。要说不通点,那就是CyclicBarrier在释放等待线程后可以重用,所以称它为循环 的 barrier。具体说明参照API,此处上代码:

    package face.thread.CountDownLatch;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.concurrent.BrokenBarrierException;
    import java.util.concurrent.CyclicBarrier;
    
    public class CyclicBarrierDemo1 {
    	
    	public static void main(String[] args) {
    		
    		final SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
    		final CyclicBarrier start = new CyclicBarrier(3,new Runnable() {
    			public void run() {
    				try {
    					System.out.println("准备就绪!");
    					Thread.sleep(1000);
    					System.out.println("开始执行!");
    				} catch (InterruptedException e) {
    					e.printStackTrace();
    				}
    			}
    		});
    		
    		final CyclicBarrier end = new CyclicBarrier(3,new Runnable() {
    			public void run() {
    				System.out.println("------执行完毕-----!");
    			}
    		});
    		
    		for(int i = 0; i < 3;i++){
    			new Thread(new Runnable() {
    				public void run() {
    					 try {
    						Thread.sleep(1000);
    						System.out.println(Thread.currentThread().getName() +"运动员准备就绪," + sdf.format(new Date()));
    						start.await();
    						
    						Thread.sleep(1000);
    						System.out.println(Thread.currentThread().getName() +"运动员结束比赛," + sdf.format(new Date()));
    						end.await();
    						
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					} catch (BrokenBarrierException e) {
    						e.printStackTrace();
    					}
    				}
    			}).start();
    		}
    	}
    }



  • 相关阅读:
    原生ajax与伪ajax
    ModelForm操作
    django学习笔记(四)
    django学习笔记(五)
    java.lang.NoClassDefFoundError: org/apache/poi/xwpf/usermodel/IRunBody异常
    springBoot项目mybatis中加入缓存
    Linux搭建MongoDB
    java搭建分布式项目
    Linux安装Apollo
    Foxmail公司邮箱配置
  • 原文地址:https://www.cnblogs.com/chen1-kerr/p/6900037.html
Copyright © 2020-2023  润新知