网站推广方法及特点,网站添加内容,瓜果类网站建设方案,百度北京总部电话Latch设计模式指定了一个屏障#xff0c;只有所有条件满足时#xff0c;门阀才能打开。Latch的作用是为了等待所有子任务完成后再执行其他任务。CountDownLatch的await超时的时候#xff0c;已经完成的任务正常结束#xff0c;未按时完成的任务不会被中断#xff0c;还会继… Latch设计模式指定了一个屏障只有所有条件满足时门阀才能打开。Latch的作用是为了等待所有子任务完成后再执行其他任务。CountDownLatch的await超时的时候已经完成的任务正常结束未按时完成的任务不会被中断还会继续执行它不提供线程管理方面的支持。 示例代码
import java.util.concurrent.TimeUnit;public abstract class Latch {
protected int limit;public Latch(int limit) {
this.limitlimit;
}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(limit0) {
this.wait();
}
}
}Override
public void countDown() {
synchronized(this) {
if(limit0) {
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(time0) {
throw new IllegalArgumentException(The time is invalid);
}
long remainNanosunit.toNanos(time);
final long endNanosSystem.nanoTime()remainNanos;
synchronized(this) {
while(limit0) {
if(TimeUnit.NANOSECONDS.toMillis(remainNanos)0) {
throw new WaitTimeoutException(The wait time over specify time.);
}
this.wait(TimeUnit.NANOSECONDS.toMillis(remainNanos));
remainNanosendNanos-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.latchlatch;
this.programmerprogrammer;
this.transportationtransportation;
}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 latchnew 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 );
}}