当前位置:网站首页>Concurrent tool set for concurrent programming
Concurrent tool set for concurrent programming
2022-07-25 13:32:00 【Ziqian 2014】
One 、CountDownLatch
Counter tool .
await
countDown
1.1 CountDownLatch Simple application
CountDownExample.java
import java.util.concurrent.CountDownLatch;
public class CountDownExample {
static CountDownLatch countDownLatch=new CountDownLatch(1);
static class Thread1 extends Thread{
@Override
public void run(){
//TODO
try {
Thread.sleep(500);
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" end of execution ");
// Means I'm done
}
}
static class Thread2 extends Thread{
@Override
public void run(){
try {
Thread.sleep(500);
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" end of execution ");
}
}
static class Thread3 extends Thread{
@Override
public void run(){
try {
Thread.sleep(500);
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" end of execution ");
}
}
public static void main(String[] args) throws InterruptedException {
Thread1 t1=new Thread1();
t1.start();
Thread2 t2=new Thread2();
t2.start();
Thread3 t3=new Thread3();
t3.start();
System.out.println(" End of main thread execution ");
countDownLatch.countDown();
}
}
1.2 CountDownLatch Business applications for
When you start the application , To do health testing for third-party applications
BaseHealthChecker.java
public abstract class BaseHealthChecker implements Runnable{
private String serviceName; // The service name
private boolean serviceUp;
public BaseHealthChecker(String serviceName) {
this.serviceName = serviceName;
}
@Override
public void run() {
try {
verifyService();
serviceUp=true;
}catch (Exception e){
serviceUp=false;
}finally {
}
}
/**
* Check the health of the service
*/
public abstract void verifyService() throws Exception;
public String getServiceName() {
return serviceName;
}
public boolean isServiceUp() {
return serviceUp;
}
}
CacheHealthChecker.java
import java.util.concurrent.CountDownLatch;
public class CacheHealthChecker extends BaseHealthChecker{
private CountDownLatch countDownLatch;
public CacheHealthChecker(CountDownLatch countDownLatch) {
super("CacheHealthChecker");
this.countDownLatch=countDownLatch;
}
@Override
public void verifyService() throws Exception {
System.out.println("Checking:"+this.getServiceName());
try {
Thread.sleep(1000);
// If the check fails ,throw RuntimeException()
} catch (Exception e) {
throw e;
}
countDownLatch.countDown();
System.out.println(this.getServiceName()+" Healthy ");
}
}
DatabaseHealthChecker.java
import java.util.concurrent.CountDownLatch;
public class DatabaseHealthChecker extends BaseHealthChecker{
private CountDownLatch countDownLatch;
public DatabaseHealthChecker(CountDownLatch countDownLatch) {
super("DatabaseHealthChecker");
this.countDownLatch=countDownLatch;
}
@Override
public void verifyService() throws Exception {
System.out.println("Checking:"+this.getServiceName());
try {
Thread.sleep(1000);
} catch (Exception e) {
throw e;
}
countDownLatch.countDown();
System.out.println(this.getServiceName()+" Healthy ");
}
}
ApplicationStartup.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class ApplicationStartup {
private static List<BaseHealthChecker> services;
private static CountDownLatch countDownLatch=new CountDownLatch(2);
static{
services=new ArrayList<>();
services.add(new CacheHealthChecker(countDownLatch));
services.add(new DatabaseHealthChecker(countDownLatch));
}
private final static ApplicationStartup INSTANCE=new ApplicationStartup();
private ApplicationStartup(){
}
public static ApplicationStartup getInstance(){
return INSTANCE;
}
public static boolean checkExternalServices() throws InterruptedException {
for(BaseHealthChecker bh:services){
new Thread(bh).start(); // For each service, threads are used to execute
}
countDownLatch.await();
return true;
}
}
StartupMain.java
public class StartupMain {
public static void main(String[] args) {
try {
ApplicationStartup.checkExternalServices();
} catch (InterruptedException e) {
// There's a problem .
}
System.out.println(" Service started successfully ");
}
}
1.3 CountDownLatch Implementation principle of
It allows a thread to block
You can also block multiple threads
Implementation of shared lock . Multiple threads can be allowed to preempt locks at the same time , Then wait until the counter returns to zero , Wake up at the same time .
state Record counter .
countDown When , It's actually state–
Two 、Semaphore
2.1 semaphore Introduce
Signal lamp .
Current limiter , Restrict access to resources .
Essentially : Seize a token , If you grab the token , Just go through , otherwise , Just block !
acquire() Seize a token
release() Release a token .
Semaphore semaphore=new Semaphore(10);
acquire = 10 - 1
by 0 When , Blocking , It is possible to block at the same time N Threads
release = token +1
There's a token , Wake up the . Wake up from blocked threads .
Why use shared locks ?
Because multiple tokens can be released at the same time , That means that multiple threads can preempt the lock at the same time .
2.2 semaphore application
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class SemaphoreExample {
public static void main(String[] args) {
// Limit the number of concurrent resources .
Semaphore semaphore=new Semaphore(10);
for (int i = 0; i < 20; i++) {
new Car(i,semaphore).start();
}
}
static class Car extends Thread{
private int num;
private Semaphore semaphore;
public Car(int num, Semaphore semaphore) {
this.num = num;
this.semaphore = semaphore;
}
@Override
public void run(){
try {
semaphore.acquire(); // Get a token
System.out.println(" The first "+num+" Two cars grab a parking space ");
TimeUnit.SECONDS.sleep(2);
System.out.println(" The first "+num+" Let's go ~");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release(); // Release a token
}
}
}
}
3、 ... and 、CyclicBarrier
Repeatable fence . The implementation is equivalent to multiple threads passing CountDownLatch Of await, Then another thread uses countDown Method to wake up .
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierExample {
public static void main(String[] args) {
int n = 4;
CyclicBarrier barrier = new CyclicBarrier(4, () -> {
System.out.println(" All threads are written , Continue with other tasks ");
}); // 4
for (int i = 0; i < n; i++) {
new Writer(barrier).start();
}
}
static class Writer extends Thread {
private CyclicBarrier cyclicBarrier;
public Writer(CyclicBarrier barrier) {
this.cyclicBarrier = barrier;
}
@Override
public void run() {
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " Write data completed , Wait for other threads ");
cyclicBarrier.await(); //-1 The action of
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}
}
边栏推荐
猜你喜欢

QGIS加载在线地图:高德、天地图等

卷积神经网络模型之——AlexNet网络结构与代码实现
![[review SSM framework series] 15 - Summary of SSM series blog posts [SSM kill]](/img/fb/6ca8e0eb57c76c515e2aae68e9e549.png)
[review SSM framework series] 15 - Summary of SSM series blog posts [SSM kill]

并发编程 — 内存模型 JMM

Shell common script: judge whether the file of the remote host exists

Based on Baiwen imx6ull_ Ap3216 experiment driven by Pro development board

ES6数组去重 new Set()

机器学习强基计划0-4:通俗理解奥卡姆剃刀与没有免费午餐定理

The interviewer asked me: how much do you know about MySQL's storage engine?

基于百问网IMX6ULL_PRO开发板驱动AP3216实验
随机推荐
mysql函数汇总之日期和时间函数
Uncaught SyntaxError: Octal literals are not allowed in strict mode.
[Video] Markov chain Monte Carlo method MCMC principle and R language implementation | data sharing
备战2022 CSP-J1 2022 CSP-S1 初赛 视频集
Docekr learning - MySQL 8 master-slave replication setup deployment
全网最简单解决方式1045-Access denied for user [email protected](using password:YES)
Design and principle of thread pool
R language GLM generalized linear model: logistic regression, Poisson regression fitting mouse clinical trial data (dose and response) examples and self-test questions
QGIS加载在线地图:高德、天地图等
mujoco_ Py Chinese document
QGIS loading online map: Gaode, Tiandi map, etc
HTTP cache tongtianpian, there may be something you want
In order to improve efficiency, there are various problems when using parallelstream
stable_baselines快速入门
Machine learning strong foundation program 0-4: popular understanding of Occam razor and no free lunch theorem
【GCN-CTR】DC-GNN: Decoupled GNN for Improving and Accelerating Large-Scale E-commerce Retrieval WWW22
The whole process of 6w+ word recording experiment | explore the economical data storage strategy of alluxio
Numpy快速入门
Convolutional neural network model -- vgg-16 network structure and code implementation
Hcip day 9 notes