当前位置:网站首页>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
边栏推荐
猜你喜欢

Talk about message oriented middleware (1) and AMQP

堆利用之chunk extend: HITCON tranining lab13

Wireshark learning notes (I) common function cases and skills

Abbexa 8-OHdG CLIA 试剂盒解决方案

mmcv之Config类介绍

聊聊远程办公那些事儿,参与征文领稿费拿大奖!

IIS installation and deployment web site
![[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

Leetcode 929. 独特的电子邮件地址

Leetcode 875. 爱吃香蕉的珂珂
随机推荐
Noise line h5js effect realized by canvas
numpy——记录
红色垂直左侧边菜单导航代码
掌握高性能计算前,我们先了解一下它的历史
YML file configuration parameter definition dictionary and list
企鹅电竞停步,虎牙也难行
第七部分:第二课 顾问通用技能-如何安装和卸载SAP ERP系统客户端
基于注解和反射生成xml
使用IdentityServer出现过SameSite Cookie这个问题吗?
.NET 开源的免费午餐结束了?
CUDA Programming (I): add two arrays
蓝桥杯_糊涂人寄信_递归
Swin_Transformer源码解读
IIS安装 部署网站
Numpy - record
电商行业转账返款方案分析
Mapbox GL development tutorial (11): loading line layers
True thesis of information system project manager in the first half of 2022
分享这位大神的WPF界面设计系列视频
LoRa模块无线收发通信技术详解