问题描述
这里有两段代码完成(我认为是)同样的事情.
here are two chunks of code that accomplish (what i think is) the same thing.
我基本上是在尝试学习如何使用 java 1.5 的并发来摆脱 thread.sleep(long).第一个示例使用 reentrantlock,第二个示例使用 countdownlatch.我想要做的主要是让一个线程进入睡眠状态,直到另一个线程解决了一个条件.
i basically am trying to learn how to use java 1.5's concurrency to get away from thread.sleep(long). the first example uses reentrantlock, and the second example uses countdownlatch. the jist of what i am trying to do is put one thread to sleep until a condition is resolved in another thread.
reentrantlock 为我用来决定是否唤醒另一个线程的布尔值提供一个锁,然后我使用带有等待/信号的 condition 来休眠另一个线程.据我所知,我需要使用锁的唯一原因是如果多个线程需要对布尔值的写访问.
the reentrantlock provides a lock on the boolean i'm using to decide whether to wake the other thread or not, and then i use the condition with await/signal to sleep the other thread. as far as i can tell, the only reason i would need to use locks is if more than one thread required write access to the boolean.
countdownlatch 似乎提供与 reentrantlock 相同的功能,但没有(不必要的?)锁.然而,感觉就像我通过只需要一个倒计时来初始化它来劫持它的预期用途.我认为它应该在多个线程要处理同一个任务时使用,而不是在多个线程正在等待一个任务时使用.
the countdownlatch seems to provide the same functionality as the reentrantlock but without the (unnecessary?) locks. however, it feels like i am kind of hijacking its intended use by initializing it with only one countdown necessary. i think it's supposed to be used when multiple threads are going to be working on the same task, not when multiple threads are waiting on one task.
所以,问题:
我是否在 reentrantlock 代码中为正确的事情"使用了锁?如果我只在一个线程中写入布尔值,是否需要锁?只要我在唤醒任何其他线程之前重置布尔值就不会导致问题,可以吗?
am i using locks for "the right thing" in the reentrantlock code? if i am only writing to the boolean in one thread, are the locks necessary? as long as i reset the boolean before waking up any other threads i can't cause a problem, can i?
是否有一个类似于 countdownlatch 的类可以用来避免更自然地适合此任务的锁(假设我应该在这种情况下避免它们)?
is there a class similar to countdownlatch i can use to avoid locks (assuming i should be avoiding them in this instance) that is more naturally suited to this task?
还有其他方法可以改进我应该注意的代码吗?
are there any other ways to improve this code i should be aware of?
示例一:
import java.util.concurrent.locks.*; public class reentrantlockexample extends thread { //boolean - is the service down? boolean servicedown; // i am using this lock to synchronize access to sdown lock servicelock; // and this condition to sleep any threads waiting on the service. condition servicecondition; public static void main(string[] args) { lock l = new reentrantlock(); condition c = l.newcondition(); reentrantlockexample rle = new reentrantlockexample(l, c); //imagine this thread figures out the service is down l.lock(); try { rle.servicedown = true; } finally { l.unlock(); } int waittime = (int) (math.random() * 5000); system.out.println("from main: wait time is " waittime); rle.start(); try { //symbolizes some random time that the service takes to come back up. thread.sleep(waittime); } catch (interruptedexception e) { e.printstacktrace(); } //imagine this thread figures out that the service is back up. l.lock(); try { rle.servicedown = false; c.signal(); } finally { l.unlock(); } } //constructor public reentrantlockexample(lock l, condition c) { this.servicelock = l; this.servicecondition = c; } /* * should wait for this imaginary service to come back online. */ public void run() { system.out.println("thread: start awaiting"); servicelock.lock(); try { while (isservicedown()) { servicecondition.await(); } } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } finally { servicelock.unlock(); } system.out.println("thread: done awaiting"); } private boolean isservicedown() { return servicedown; } }
示例二:
import java.util.concurrent.countdownlatch; import java.util.concurrent.timeunit; import java.util.concurrent.locks.*; public class countdownlatchexample extends thread { //boolean - is the service down? boolean servicedown; // i am using this latch to wait on the service. countdownlatch servicelatch; public static void main(string[] args) { countdownlatch cdl = new countdownlatch(1); countdownlatchexample cdle = new countdownlatchexample(cdl); //service goes down. cdle.servicedown = true; int waittime = (int) (math.random() * 5000); system.out.println("from main: wait time is " waittime); cdle.start(); try { //symbolizes some random time that the service takes to come back up. thread.sleep(waittime); } catch (interruptedexception e) { e.printstacktrace(); } //service comes back up. cdle.servicedown = false; cdl.countdown(); } //constructor public countdownlatchexample(countdownlatch cdl) { this.servicelatch = cdl; } /* * should wait for this imaginary service to come back online. */ public void run() { system.out.println("thread: start awaiting"); try { while (isservicedown()) { servicelatch.await(); } } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } system.out.println("thread: done awaiting"); } private boolean isservicedown() { return servicedown; } }
推荐答案
这两种方法大致等效,除了 countdownlatch 只能释放一次.之后所有 await() 调用立即返回.所以 cyclicbarrier 实际上可能更多如果您使用的服务可能会下降和上升,则适用.
either approach is roughly equivalent, except that a countdownlatch can only be released once. after that all await() calls return instantly. so a cyclicbarrier may actually be more appropriate if you are working with a service that may go down and up.
如果您的条件确实是一次**易,那么 futuretask 会更合适.您可以调用 get() 这将等待服务可用,然后您可以在 get() 返回后立即使用该服务.
if your condition really is a one-shot deal, then a futuretask would be more appropriate. you could call get() which would wait for the service to become available, and then you could use the service as soon as get() returns.
您提到 countdownlatch 允许在不使用锁的情况下等待.但是,countdownlatch 和 reentrantlock 使用 abstractqueuedsynchronizer 实现.在底层,它们提供相同的同步和可见性语义.
you mention that countdownlatch allows waiting without using locks. however, both countdownlatch and reentrantlock are implemented using abstractqueuedsynchronizer. under the hood, they provide identical synchronization and visibility semantics.