`

CyclicBarrier与CountDownLatch、栅栏与计数器

阅读更多

在多线程设计中,我猜常常会遇到线程间相互等待以及某个线程等待1个或多个线程的场景,比如多线程精密计算和大量数据处理,这里写下我自己的体会和理解。

   

    我想应该有很多办法,如果是简单的1:1关系,那么可以wait()和notify()解决,就像一把锁和一把钥匙;如果是1:N关系,这个1就需要关心N的所有状态了,最笨的办法是1可以去查看N当前的状态,轮询询问工作是否做完。而好点的办法是N做完后主动告诉1,然后N就会有2种选择,要么听从1的命令,要么继续干自己其他的活。

 

    用传统的方法我想应该是都能实现的,而JDK1.5提供了CyclicBarrier与CountDownLatch来解决了这两个问题,而她们的区别是:

    CyclicBarrier使所有线程相互等待,而CountDownLatch使一个或多个线程等待其他线程。区别类似上面蓝色字体,CountDownLatch不会等待其他线程了,只要做完自己的工作就干自己的活去了,也就是run()方法里其他的任务。

 

Example:

Java代码 复制代码 收藏代码
  1. public static void testCountDownLatch() throws InterruptedException{   
  2.   CountDownLatch cdl=new CountDownLatch(2);   
  3.   ExecutorService exe=Executors.newFixedThreadPool(2);   
  4.    class Bow implements  Runnable{   
  5.     CountDownLatch cdl;   
  6.     public Bow(CountDownLatch cdl){   
  7.     this.cdl=cdl;    
  8.     }   
  9.     public void run(){   
  10.      System.out.println("The bow is coming");   
  11.      System.out.println("kick a bow ");   
  12.      this.cdl.countDown();   
  13.      System.out.println("do other thing");   
  14.      }   
  15.    }   
  16.   exe.execute(new Bow(cdl));   
  17.   exe.execute(new Bow(cdl));   
  18.   exe.shutdown();   
  19.   System.out.println("Wait...");   
  20.     cdl.await();   
  21.     System.out.println("End..");   
  22.     
  23.  }   
  24.   
  25.     public static void main(String[] args) {   
  26.         try {   
  27.             Test.testCountDownLatch();   
  28.         } catch (InterruptedException e) {   
  29.         }   
  30.     }  
public static void testCountDownLatch() throws InterruptedException{
  CountDownLatch cdl=new CountDownLatch(2);
  ExecutorService exe=Executors.newFixedThreadPool(2);
   class Bow implements  Runnable{
    CountDownLatch cdl;
    public Bow(CountDownLatch cdl){
    this.cdl=cdl; 
    }
    public void run(){
     System.out.println("The bow is coming");
     System.out.println("kick a bow ");
     this.cdl.countDown();
     System.out.println("do other thing");
     }
   }
  exe.execute(new Bow(cdl));
  exe.execute(new Bow(cdl));
  exe.shutdown();
  System.out.println("Wait...");
    cdl.await();
    System.out.println("End..");
 
 }

	public static void main(String[] args) {
		try {
			Test.testCountDownLatch();
		} catch (InterruptedException e) {
		}
	}

 

输出的结果为:

 

The bow is coming
kick a bow
do other thing
Wait...
The bow is coming
kick a bow
do other thing
End..

 

如上所说do other thing不受影响。

 

写了一个CyclicBarrier的例子:

Java代码 复制代码 收藏代码
  1. public static void testCyclicBarrier() throws InterruptedException, BrokenBarrierException{   
  2.         CyclicBarrier barr=new CyclicBarrier(2+1);   
  3.            
  4.         ExecutorService exe=Executors.newFixedThreadPool(2);   
  5.          class Bow implements  Runnable{   
  6.              CyclicBarrier barr;   
  7.                 public Bow(CyclicBarrier barr){   
  8.                 this.barr=barr;    
  9.                 }   
  10.                 public void run(){   
  11.                     System.out.println("The bow is coming");   
  12.                     System.out.println("kick a down");   
  13.                     try {   
  14.                         barr.await();   
  15.                     } catch (InterruptedException e) {   
  16.                         // TODO Auto-generated catch block   
  17.                         e.printStackTrace();   
  18.                     } catch (BrokenBarrierException e) {   
  19.                         // TODO Auto-generated catch block   
  20.                         e.printStackTrace();   
  21.                     }   
  22.                     System.out.println("do other thing");   
  23.                     }   
  24.             }   
  25.         exe.execute(new Bow(barr));   
  26.         exe.execute(new Bow(barr));   
  27.         exe.shutdown();   
  28.         System.out.println("Wait...");   
  29.         barr.await();   
  30.        System.out.println("End..");   
  31.        
  32.     }   
  33.   
  34.   
  35.     public static void main(String[] args) {   
  36.         try {   
  37.             Test.testCyclicBarrier();   
  38.         } catch (InterruptedException e) {   
  39.         }   
  40.         catch (BrokenBarrierException e) {   
  41.         }   
  42.     }  
public static void testCyclicBarrier() throws InterruptedException, BrokenBarrierException{
	    CyclicBarrier barr=new CyclicBarrier(2+1);
		
		ExecutorService exe=Executors.newFixedThreadPool(2);
		 class Bow implements  Runnable{
			 CyclicBarrier barr;
				public Bow(CyclicBarrier barr){
				this.barr=barr;	
				}
				public void run(){
					System.out.println("The bow is coming");
					System.out.println("kick a down");
					try {
						barr.await();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (BrokenBarrierException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println("do other thing");
					}
			}
		exe.execute(new Bow(barr));
		exe.execute(new Bow(barr));
		exe.shutdown();
		System.out.println("Wait...");
		barr.await();
	   System.out.println("End..");
	
	}


	public static void main(String[] args) {
		try {
			Test.testCyclicBarrier();
		} catch (InterruptedException e) {
		}
		catch (BrokenBarrierException e) {
		}
	}

 

输出结果为:

 

Wait...
The bow is coming
kick a down
The bow is coming
kick a down
do other thing
End..
do other thing

 

这应该是CyclicBarrier吧?
兄弟你的例子来说明问题似乎让人不好琢磨。我也写了两个例子,大家一起学习下

Java代码 复制代码 收藏代码
  1. public class CyclicBarrierTest {   
  2.   
  3.     public static void main(String[] args) {   
  4.         ExecutorService service = Executors.newCachedThreadPool();   
  5.         final  CyclicBarrier cb = new CyclicBarrier(3);//构造方法里的数字标识有几个线程到达集合地点开始进行下一步工作   
  6.         for(int i=0;i<3;i++){   
  7.             Runnable runnable = new Runnable(){   
  8.                     public void run(){   
  9.                     try {   
  10.                         Thread.sleep((long)(Math.random()*10000));     
  11.                         System.out.println("线程" + Thread.currentThread().getName() +    
  12.                                 "即将到达集合地点1,当前已有" + cb.getNumberWaiting() + "个已经到达,正在等候");                          
  13.                         cb.await();   
  14.                            
  15.                         Thread.sleep((long)(Math.random()*10000));     
  16.                         System.out.println("线程" + Thread.currentThread().getName() +    
  17.                                 "即将到达集合地点2,当前已有" + cb.getNumberWaiting() + "个已经到达,正在等候");                          
  18.                         cb.await();    
  19.                         Thread.sleep((long)(Math.random()*10000));     
  20.                         System.out.println("线程" + Thread.currentThread().getName() +    
  21.                                 "即将到达集合地点3,当前已有" + cb.getNumberWaiting() + "个已经到达,正在等候");                          
  22.                         cb.await();                        
  23.                     } catch (Exception e) {   
  24.                         e.printStackTrace();   
  25.                     }                  
  26.                 }   
  27.             };   
  28.             service.execute(runnable);   
  29.                
  30.         }   
  31.         service.shutdown();   
  32.     }   
  33.        
  34. }  
public class CyclicBarrierTest {

	public static void main(String[] args) {
		ExecutorService service = Executors.newCachedThreadPool();
		final  CyclicBarrier cb = new CyclicBarrier(3);//构造方法里的数字标识有几个线程到达集合地点开始进行下一步工作
		for(int i=0;i<3;i++){
			Runnable runnable = new Runnable(){
					public void run(){
					try {
						Thread.sleep((long)(Math.random()*10000));	
						System.out.println("线程" + Thread.currentThread().getName() + 
								"即将到达集合地点1,当前已有" + cb.getNumberWaiting() + "个已经到达,正在等候");						
						cb.await();
						
						Thread.sleep((long)(Math.random()*10000));	
						System.out.println("线程" + Thread.currentThread().getName() + 
								"即将到达集合地点2,当前已有" + cb.getNumberWaiting() + "个已经到达,正在等候");						
						cb.await();	
						Thread.sleep((long)(Math.random()*10000));	
						System.out.println("线程" + Thread.currentThread().getName() + 
								"即将到达集合地点3,当前已有" + cb.getNumberWaiting() + "个已经到达,正在等候");						
						cb.await();						
					} catch (Exception e) {
						e.printStackTrace();
					}				
				}
			};
			service.execute(runnable);
			
		}
		service.shutdown();
	}
	
}



 

Java代码 复制代码 收藏代码
  1. public class CountdownLatchTest {   
  2.   
  3.     public static void main(String[] args) {   
  4.         ExecutorService service = Executors.newCachedThreadPool();   
  5.         final CountDownLatch cdOrder = new CountDownLatch(1);   
  6.         final CountDownLatch cdAnswer = new CountDownLatch(3);         
  7.         for(int i=0;i<3;i++){   
  8.             Runnable runnable = new Runnable(){   
  9.                     public void run(){   
  10.                     try {   
  11.                         System.out.println("线程" + Thread.currentThread().getName() +    
  12.                                 "正准备接受命令");                        
  13.                         cdOrder.await();   
  14.                         System.out.println("线程" + Thread.currentThread().getName() +    
  15.                         "已接受命令");                                  
  16.                         Thread.sleep((long)(Math.random()*10000));     
  17.                         System.out.println("线程" + Thread.currentThread().getName() +    
  18.                                 "回应命令处理结果");                           
  19.                         cdAnswer.countDown();                          
  20.                     } catch (Exception e) {   
  21.                         e.printStackTrace();   
  22.                     }                  
  23.                 }   
  24.             };   
  25.             service.execute(runnable);   
  26.         }          
  27.         try {   
  28.             Thread.sleep((long)(Math.random()*10000));   
  29.            
  30.             System.out.println("线程" + Thread.currentThread().getName() +    
  31.                     "即将发布命令");                         
  32.             cdOrder.countDown();   
  33.             System.out.println("线程" + Thread.currentThread().getName() +    
  34.             "已发送命令,正在等待结果");       
  35.             cdAnswer.await();   
  36.             System.out.println("线程" + Thread.currentThread().getName() +    
  37.             "已收到所有响应结果");      
  38.         } catch (Exception e) {   
  39.             e.printStackTrace();   
  40.         }                  
  41.         service.shutdown();   
  42.   
  43.     }   
  44. }  

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics