当前位置:网站首页>This article introduces you to j.u.c's futuretask, fork/join framework and BlockingQueue
This article introduces you to j.u.c's futuretask, fork/join framework and BlockingQueue
2022-06-10 18:07:00 【InfoQ】
FutureTask
Callable And Runnable Interface comparison
Future Interface
FutureTask class
package io.binghe.concurrency.example.aqs;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
@Slf4j
public class FutureExample {
static class MyCallable implements Callable<String>{
@Override
public String call() throws Exception {
log.info("do something in callable");
Thread.sleep(5000);
return "Done";
}
}
public static void main(String[] args) throws Exception {
ExecutorService executorService = Executors.newCachedThreadPool();
Future<String> future = executorService.submit(new MyCallable());
log.info("do something in main");
Thread.sleep(1000);
String result = future.get();
log.info("result: {}", result);
executorService.shutdown();
}
}
package io.binghe.concurrency.example.aqs;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
@Slf4j
public class FutureTaskExample {
public static void main(String[] args) throws Exception{
FutureTask<String> futureTask = new FutureTask<String>(new Callable<String>() {
@Override
public String call() throws Exception {
log.info("do something in callable");
Thread.sleep(5000);
return "Done";
}
});
new Thread(futureTask).start();
log.info("do something in main");
Thread.sleep(1000);
String result = futureTask.get();
log.info("result: {}", result);
}
} Copy Fork/Join frame
Why use a job stealing algorithm ?
Advantages of job theft algorithm :
Disadvantages of job stealing algorithm :
Fork/Join Framework limitations :
Fork/Join Core classes of framework
package io.binghe.concurrency.example.aqs;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;
@Slf4j
public class ForkJoinTaskExample extends RecursiveTask<Integer> {
public static final int threshold = 2;
private int start;
private int end;
public ForkJoinTaskExample(int start, int end) {
this.start = start;
this.end = end;
}
@Override
protected Integer compute() {
int sum = 0;
// If the task is small enough, calculate the task
boolean canCompute = (end - start) <= threshold;
if (canCompute) {
for (int i = start; i <= end; i++) {
sum += i;
}
} else {
// If the task is greater than the threshold , Split it into two subtasks
int middle = (start + end) / 2;
ForkJoinTaskExample leftTask = new ForkJoinTaskExample(start, middle);
ForkJoinTaskExample rightTask = new ForkJoinTaskExample(middle + 1, end);
// Perform subtasks
leftTask.fork();
rightTask.fork();
// Its merge task is finished
int leftResult = leftTask.join();
int rightResult = rightTask.join();
// Merge subtasks
sum = leftResult + rightResult;
}
return sum;
}
public static void main(String[] args) {
ForkJoinPool forkjoinPool = new ForkJoinPool();
// Generate a calculation task , Calculation 1+2+3+4
ForkJoinTaskExample task = new ForkJoinTaskExample(1, 100);
// Perform a task
Future<Integer> result = forkjoinPool.submit(task);
try {
log.info("result:{}", result.get());
} catch (Exception e) {
log.error("exception", e);
}
}
}BlockingQueue
The blocking conditions are as follows :
The usage scenario is as follows :
BlockingQueue Methods

- Throw an exception
- Special values
- Blocking
- Overtime
BlockingQueue The implementation classes of are as follows :
- ArrayBlockingQueue: Bounded blocking queues ( Limited capacity , The capacity size must be specified during initialization , The capacity cannot be changed after it is specified ), The internal implementation is an array , With FIFO How to store data , The most recently inserted object is the tail , The most recently removed object is the head .
- DelayQueue: What's blocking is the internal elements ,DelayQueue The element in must implement an interface ——Delayed( Exist in J.U.C Next ).Delayed Interface inherited Comparable Interface , This is because Delayed The elements in the interface need to be sorted , In general , This is the Delayed The elements in the interface are sorted according to the priority of expiration time . Application scenarios mainly include : Close the connection regularly 、 Cache object 、 Timeout processing, etc . Internal implementation uses PriorityQueue and ReentrantLock.
- LinkedBlockingQueue: Size configuration is optional , If the size is specified during initialization , There are boundaries ; If no size is specified during initialization , Is boundless ( In fact, the default size is Integer Maximum of type ). Internal implementation is a linked list , With FIFO How to store data , The most recently inserted object is the tail , The most recently removed object is the head .
- PriorityBlockingQueue: Blocking queue with priority , Borderless , But there are sorting rules , Allow inserting empty objects ( That is to say null). All inserted objects must implement Comparable Interface , The sorting rule of queue priority is based on Comparable Interface . It can be downloaded from PriorityBlockingQueue Get an iterator in Iterator, But this iterator does not guarantee that iterations are performed in order of priority .
- SynchronousQueue: Only one element is allowed inside the queue , When a thread inserts an element , Will be blocked , Unless this element is consumed by another thread . therefore , Also known as SynchronousQueue For synchronization queue .SynchronousQueue Is an unbounded non cached queue . Accurately speaking , It does not store elements , Put in the element only after waiting for the element to be taken away , To put in the elements again
边栏推荐
- pands pd. Detailed parsing of dataframe() function
- AI 加持实时互动|ZegoAvatar 面部表情随动技术解析
- Linear mobile chess
- 凹印套印原理及影响套印的因素
- 待办事项桌面插件,办公族的桌面好帮手
- Open source project PM how to design official website
- well! One new star, please look over | elder martial brother and elder martial sister say
- 2022上半年信息系统项目管理师论文真题
- CUDA编程(一):实现两个数组相加
- Abbexa 细菌基因组 DNA 试剂盒介绍
猜你喜欢

js锚点定位可以扩展很多功能

蓝桥杯_挑选子串_组合数学_乘法原理_ / 尺取法

IIS installation and deployment web site

Leetcode 875. Coco, who likes bananas

聊聊远程办公那些事儿,参与征文领稿费拿大奖!
![[FAQ] summary of common problems and solutions during the use of rest API interface of sports health service](/img/93/d999239b28afb2d9a61e9aad27d2cd.png)
[FAQ] summary of common problems and solutions during the use of rest API interface of sports health service

js模糊阴影跟随动画js特效插件

mmdetection之dataset类解读

PCA principal component analysis tutorial (origin analysis & drawing, without R language)

如何定位游戏发热问题
随机推荐
美学心得(第二百三十七集) 罗国正
com. netflix. client. ClientException: Load balancer does not have available server for client: userser
Mapbox GL development tutorial (11): loading line layers
yml文件配置参数定义字典和列表
内存池原理一(基于整块)
使用IdentityServer出现过SameSite Cookie这个问题吗?
Analysis of transfer Refund Scheme in e-commerce industry
Vim常用命令总结
CodeCraft-22 and Codeforces Round #795 (Div. 2)
Flutter在数字生活的发展与天翼云盘落地实践
Draw confusion matrix
The short ticket hypothesis: finding sparse, trainable neural networks
cocoeval函数使用
安装Linux系统的MySQL,在xshell中遇见的问题
mmdetection之dataset类解读
canvas发散的粒子h5动画js特效
凹印套印原理及影响套印的因素
云计算搭建全部内容总结,保证可以搭建一个完整的云计算服务器,包括节点安装、实例的分配和网络的配置等内容
There is an urgent need to enrich the smart home product line. Can fluorite be crowded on the sweeping robot track?
Canvas fire burning H5 animation JS special effects