计数器设计模式CountDown设计模式

编程

JDK自带的CountDownLatch 很容易的实现了这一个功能,先看jdk怎么实现的

package com.thread.ch14;

import java.util.Random;

import java.util.concurrent.CountDownLatch;

import java.util.stream.IntStream;

public class JdkCountDown {

private static final Random random = new Random(System.currentTimeMillis());

public static void main(String[] args) throws InterruptedException {

CountDownLatch latch = new CountDownLatch(4);

//第一步線程操作

IntStream.range(1, 5).forEach(i -> {

new Thread(() -> {

System.out.println(Thread.currentThread().getName() + " is working");

try {

Thread.sleep(random.nextInt(1000));

} catch (InterruptedException e) {

e.printStackTrace();

}

latch.countDown();

},String.valueOf(i)).start();

});

latch.await();

//第二部提交結果

System.out.println("多线程任务全部结束,准备第二阶段任务");

System.out.println("............");

System.out.println("FINISH");

}

}

打印结果:

1 is working
2 is working
4 is working
3 is working
多线程任务全部结束,准备第二阶段任务
............
FINISH

自己是实现一个countDown

package com.thread.ch14;

public class CountDown {

//次數

private int count = 1;

//總次數

private int total;

public CountDown(int total) {

this.total = total;

}

public void down() {

synchronized (this) {

this.count++;

System.out.println("down-----"+Thread.currentThread().getName());

this.notifyAll();

}

}

public void await() throws InterruptedException {

synchronized (this) {

while (count <= total) {

this.wait();

}

}

}

}

package com.thread.ch14;

import java.util.Random;

import java.util.concurrent.CountDownLatch;

import java.util.stream.IntStream;

public class CountDownClient {

private static final Random random = new Random(System.currentTimeMillis());

public static void main(String[] args) throws InterruptedException {

CountDown latch = new CountDown(4);

//第一步線程操作

IntStream.range(1, 5).forEach(i -> {

new Thread(() -> {

System.out.println(Thread.currentThread().getName() + " is working");

try {

Thread.sleep(random.nextInt(1000));

} catch (InterruptedException e) {

e.printStackTrace();

}

latch.down();

},String.valueOf(i)).start();

});

latch.await();

//第二部提交結果

System.out.println("多线程任务全部结束,准备第二阶段任务");

System.out.println("............");

System.out.println("FINISH");

}

}

打印结果一样

1 is working
2 is working
4 is working
3 is working
down-----4
down-----2
down-----1
down-----3
多线程任务全部结束,准备第二阶段任务
............
FINISH
 

 

 

以上是 计数器设计模式CountDown设计模式 的全部内容, 来源链接: utcz.com/z/513736.html

回到顶部