27SynchronizationMechanisms - CS108, Stanford Winter 2012...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Handout #27 Winter 2012 Young Java Synchronization Mechanisms Java provides a number of mechanisms for synchronizing threads. These mechanisms are found in the java.util.concurrent package. CountDownLatch The CountDownLatch is a simple means of having a thread wait until a number of tasks have been completed by other threads. We begin by creating the latch and placing it in a location where it will be visible to the other threads we are working with. The latch starts with a counter, representing the number of actions which we want to wait for. Our main thread starts the other threads and then calls await . This halts the main thread until all the other threads have completed their tasks. Here’s an example from our Synchronized Collections lecture of a CountDownLatch in actual use. static CountDownLatch latch; public static void testThreadingSupport(int numThreads) { latch = new CountDownLatch(numThreads); for(int i=0; i< numThreads; i++) { new TestListThread().start(); } try { latch.await(); } catch (InterruptedException e) { } } In each of the test threads, I simply call countDown on the latch when they have completed their task. Here’s the code: public void run() { … // do stuff latch.countDown(); } Each call to countDown reduces the value of the latch. When the value drops to zero, any threads waiting on the latch are allowed to continue. A few additional points on the latch:
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 02/12/2012 for the course CS 108 taught by Professor Jimenez during the Winter '08 term at Stanford.

Page1 / 5

27SynchronizationMechanisms - CS108, Stanford Winter 2012...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online