JAva同時制御

14051 ワード

JAva同時制御使用シーンは,マルチスレッド処理過程において,スレッド間のデータ処理の同期をどのように実現するかである.jdk 1.5以降、2つのツールが用意されています. CyclicBarrier & CountDownlatch
CyclicBarrier
  • 原理CyclicBarrierの作用公式サイトは以下のように説明する:
    A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.   
    CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. 
    The barrier is called cyclic because it can be re-used after the waiting threads are released. 
    
    説明:1組のスレッドの中で作用して、1組のスレッドが1つの同じ状態
  • に達することができるようにする
  • example
  • コード
  • public class CyclicBarrierTest {
    	public static void main(String[] args) throws InterruptedException {
    		//    barrier        
    		CyclicBarrier barrier = new CyclicBarrier(5);
    
    		//       
    		ExecutorService service = new ThreadPoolExecutor(10, 10,
    				100000, TimeUnit.DAYS, new LinkedBlockingQueue<>());
    
    		//      todo something
    		service.execute(new RunTest(0, barrier));
    		service.execute(new RunTest(1, barrier));
    		service.execute(new RunTest(2, barrier));
    		service.execute(new RunTest(3, barrier));
    		service.execute(new RunTest(4, barrier));
    
    		// terminate executor service
    		service.awaitTermination(1000, TimeUnit.SECONDS);
    		service.shutdown(); // shutdown service
    	}
    
    	static class RunTest implements Runnable {
    		int no; // number
    		CyclicBarrier barrier;
    
    		public RunTest(int num, CyclicBarrier barrier) {
    			this.no = num;
    			this.barrier = barrier;
    		}
    
    		@Override
    			public void run() {
    				// do some work
    				System.err.println("NO. " + no + " is ready for running !!!");
    				try {
    					barrier.await();
    				} catch (InterruptedException e) {
    					e.printStackTrace();
    					return;
    				} catch (BrokenBarrierException e) {
    					e.printStackTrace();
    					return;
    				}
    				System.err.println("NO. " + no + " running!!!!!");
    			}
    	}
    }
    
  • result
  • NO. 0 is ready for running !!!
    NO. 1 is ready for running !!!
    NO. 2 is ready for running !!!
    NO. 3 is ready for running !!!
    NO. 4 is ready for running !!!
    NO. 0 running!!!!!
    NO. 4 running!!!!!
    NO. 1 running!!!!!
    NO. 2 running!!!!!
    NO. 3 running!!!!!
    
  • explanation barrierが存在するため、タスクに参加するすべてのスレッドは、タスクが割り当てられた残りのスレッドが指定された場所まで実行されるのを待たなければなりません.そうしないと、残りのスレッドは適用シーンの説明を待たなければなりません. await 以前のタスクは並列化でき、その後も並列化できますが、中間のステータスは一致する必要があります.

  • CountDownLatch
  • 原理公式サイトは以下のように説明する:
    A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
    
    説明:同期ロック、具体的には同期カウンタに対応し、1つ以上のスレッドが
  • を完了するのを待つ.
  • example
  • コード
  • public class CountDownLatchTest {
    	public static void main(String[] args) throws InterruptedException {
    		//    barrier        
    		CountDownLatch latch = new CountDownLatch(5);
    
    		//       
    		ExecutorService service = new ThreadPoolExecutor(10, 10,
    				100000, TimeUnit.DAYS, new LinkedBlockingQueue<>());
    
    		service.execute(new RunTaskTest(0, latch));
    		service.execute(new RunTaskTest(1, latch));
    		service.execute(new RunTaskTest(2, latch));
    		service.execute(new RunTaskTest(3, latch));
    		service.execute(new RunTaskTest(4, latch));
    
    		latch.await(); //          
    		System.err.println("count down latch number " + latch.getCount());
    		service.shutdown(); //      
    	}
    
    	static class RunTaskTest implements Runnable {
    		int no; // number
    		CountDownLatch latch;
    
    		public RunTaskTest(int num, CountDownLatch latch) {
    			this.no = num;
    			this.latch = latch;
    		}
    
    		@Override
    			public void run() {
    				// do some work
    				System.err.println("NO. " + no + " is to count down");
    				latch.countDown(); //     - 1
    			}
    	}
    }
    
  • result
  • NO. 0 is to count down
    NO. 1 is to count down
    NO. 2 is to count down
    NO. 3 is to count down
    NO. 4 is to count down
    count down latch number 0
    
  • explanationは、残りのスレッドまたはスレッドタスクのセットの完了を待つために使用されますが、カウンタとしても使用できます. ただしincrementはcountDown
  • しかできません

    結論
    CyclicBarrierとCountDownLatchはそれぞれ1つのスレッドを待つか1つのスレッドの完了を待つかに対応し、CyclicBarrierは1つのスレッドの間で互いに待つが、CountDownLatchは1つのスレッドだけが残りのスレッドの完了を待つタスクシーンである.