本文主要是介绍Latch(门阀)设计模式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Latch设计模式指定了一个屏障,只有所有条件满足时,门阀才能打开。Latch的作用是为了等待所有子任务完成后再执行其他任务。CountDownLatch的await超时的时候,已经完成的任务正常结束,未按时完成的任务不会被中断,还会继续执行,它不提供线程管理方面的支持。
示例代码:
import java.util.concurrent.TimeUnit;public abstract class Latch {
protected int limit;public Latch(int limit) {
this.limit=limit;
}public abstract void await() throws InterruptedException;
public abstract void await(TimeUnit unit,long time) throws InterruptedException,WaitTimeoutException;
public abstract void countDown();
public abstract int getUnarrived();
}
import java.util.concurrent.TimeUnit;public class CountDownLatch extends Latch{public CountDownLatch(int limit) {
super(limit);
}@Override
public void await() throws InterruptedException {
synchronized(this) {
while(limit>0) {
this.wait();
}
}
}@Override
public void countDown() {
synchronized(this) {
if(limit<=0) {
throw new IllegalStateException("all of task already arrived");
}
limit--;
this.notifyAll();
}
}@Override
public int getUnarrived() {
return limit;
}@Override
public void await(TimeUnit unit, long time) throws InterruptedException, WaitTimeoutException {
if(time<=0) {
throw new IllegalArgumentException("The time is invalid");
}
long remainNanos=unit.toNanos(time);
final long endNanos=System.nanoTime()+remainNanos;
synchronized(this) {
while(limit>0) {
if(TimeUnit.NANOSECONDS.toMillis(remainNanos)<=0) {
throw new WaitTimeoutException("The wait time over specify time.");
}
this.wait(TimeUnit.NANOSECONDS.toMillis(remainNanos));
remainNanos=endNanos-System.nanoTime();
}
}
}}
public class WaitTimeoutException extends Exception{
public WaitTimeoutException(String message) {
super(message);
}
}
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;public class ProgrammerTravel extends Thread{
private final Latch latch;
private final String programmer;
private final String transportation;public ProgrammerTravel(Latch latch,String programmer,String transportation) {
this.latch=latch;
this.programmer=programmer;
this.transportation=transportation;
}@Override
public void run() {
System.out.println(programmer+" start take the transportation["+transportation+"]");
try {
TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(0, 10));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(programmer+" arrived by "+transportation);
latch.countDown();
}}
import java.util.concurrent.TimeUnit;public class LatchTest {public static void main(String[] args) throws InterruptedException, WaitTimeoutException {
Latch latch=new CountDownLatch(4);
new ProgrammerTravel(latch,"Alex","Bus").start();
new ProgrammerTravel(latch,"Bee","Walking").start();
new ProgrammerTravel(latch,"Charlie","Subway").start();
new ProgrammerTravel(latch,"Digo","Bicycle").start();
latch.await(TimeUnit.SECONDS,5);
System.out.println("==== all programmer arrived ====");
}}
这篇关于Latch(门阀)设计模式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!