当前位置:网站首页>JUC learning
JUC learning
2022-07-01 03:15:00 【Skinhead Xiaoqiang 007】
List of articles
️ Basic concepts
Concurrent (concurrent): On the same processor , Processing multiple tasks .
parallel (parallel): Processing multiple tasks simultaneously on multiple processors .
process : The application running in the system is a process , Each process has its own memory space and system resources .
Threads : Also known as Lightweight process , There will be one or more threads in the same process , It is the basic unit of timing scheduling in most operating systems .
Tube side :Monitor( The monitor ) , That is what we usually call a lock . It's a synchronization mechanism , At the same time , Only one thread can access protected data and code .
User threads :user thread, System worker threads , It will complete the business operations to be completed by the program .
The guardian thread :daemon thread, Is a special thread , Services for other threads , Complete a series of system tasks by default in the background .( gc Recycling mechanism )
The method to determine whether a thread is a daemon thread :
/** * Tests if this thread is a daemon thread. * * @return <code>true</code> if this thread is a daemon thread; * <code>false</code> otherwise. * @see #setDaemon(boolean) */
public final boolean isDaemon() {
return daemon;
}
User thread code demonstration and summary
Threads created by default , Are all user threads !
chestnuts :
// User threads
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"\t The current thread starts running \t"+(Thread.currentThread().isDaemon()?" guardian ":" user "));
while (true){
}
}
},"t1").start();
try {
TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) {
e.printStackTrace(); }
System.out.println(Thread.currentThread().getName()+"\t The current thread starts running ---- end The main thread ");
}
// The guardian thread
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "\t The current thread starts running \t" + (Thread.currentThread().isDaemon() ? " guardian " : " user "));
while (true) {
}
}
}, "t1");
thread.setDaemon(true);
thread.start();
try {
TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) {
e.printStackTrace(); }
System.out.println(Thread.currentThread().getName()+"\t The current thread starts running ---- end The main thread ");
}
SUM: If all user threads end , Then the business operations that the program needs to complete have ended . The guardian thread follows JVM Finish the work together .
️ CompletableFuture
️ Future Interface
Future Interface (FutureTask Implementation class ), Defined operations Asynchronous task execution Methods , For example, get the execution result of asynchronous task , Cancel the execution of the task , Judge whether the task is cancelled , Determine if the task has been completed . That is to say Future Interface can open a branch task for the main thread , Specialized in processing time-consuming and laborious complex business for the main thread .
effect :Future Interface is java5 New interface in , It provides a kind of Asynchronous parallel computing The function of . If the main thread needs to perform a time-consuming computing task , We can go through Future Put this task into an asynchronous thread to execute . The main thread will continue to process other tasks or end first , Through Future Get calculation results .
️ FutureTask
There are three characteristics of asynchronous multithreaded task execution and return results :
- Multithreading
- Back again
- Asynchronous task
Runnable Interface VSCallable Interface
- Override method names are different ,
Callable——call,Runnable——run. RunnableNo return value, no exception thrown ,CallableThere is a return value , And throw an exception .
Examples of use :
public class CompletableFutureDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<String> task = new FutureTask<>(new MyThread2());
Thread thread = new Thread(task, "t1");
thread.start();
// Get the return result of the task
System.out.println(task.get());
}
}
class MyThread2 implements Callable<String> {
@Override
public String call() throws Exception {
return null;
}
}
advantage :future + Thread pool asynchronous multithreading task coordination , It can significantly improve the execution efficiency of the program .
Example :
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 3 A mission , At present, multiple asynchronous tasks are started to process , How long does it take
ExecutorService pool = Executors.newFixedThreadPool(3);
long start = System.currentTimeMillis();
FutureTask<String> task1 = new FutureTask<String>(()->{
try {
TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) {
e.printStackTrace(); }
return "task1 over";
});
pool.submit(task1);
FutureTask<String> task2 = new FutureTask<String>(()->{
try {
TimeUnit.MILLISECONDS.sleep(300); } catch (InterruptedException e) {
e.printStackTrace(); }
return "task2 over";
});
pool.submit(task2);
task1.get();
task2.get();
try {
TimeUnit.MILLISECONDS.sleep(300); } catch (InterruptedException e) {
e.printStackTrace(); }
long end = System.currentTimeMillis();
pool.shutdown();
System.out.println(" Time consuming : " + (end-start));
System.out.println(Thread.currentThread().getName()+"-------- end");
}
public static void m1(){
// 3 A mission , There is currently only one thread main To deal with it , How long does it take
long start = System.currentTimeMillis();
try {
TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) {
e.printStackTrace(); }
try {
TimeUnit.MILLISECONDS.sleep(300); } catch (InterruptedException e) {
e.printStackTrace(); }
try {
TimeUnit.MILLISECONDS.sleep(300); } catch (InterruptedException e) {
e.printStackTrace(); }
long end = System.currentTimeMillis();
System.out.println(" Time consuming : " + (end-start));
System.out.println(Thread.currentThread().getName()+"-------- end");
}
shortcoming :
get()Method , It is easy to cause program blocking , It is generally recommended to put it at the end of the procedure ,get(long, TimeUnit)Method , After waiting for more than a few seconds, there will be no further blocking .
public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
FutureTask<String> task = new FutureTask<String>(()->{
System.out.println(Thread.currentThread().getName()+"---- come in");
TimeUnit.SECONDS.sleep(5);
return "task over";
});
new Thread(task,"t1").start();
// System.out.println(task.get());'
System.out.println(task.get(6,TimeUnit.SECONDS));
System.out.println(Thread.currentThread().getName()+"----- To do something else ");
}
isDown()polling , It will cost fearlesscpuresources , It is not possible to get results in time . If you want to get results asynchronously , Results are usually obtained by polling , Try not to block .
public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
FutureTask<String> task = new FutureTask<String>(() -> {
System.out.println(Thread.currentThread().getName() + "---- come in");
TimeUnit.SECONDS.sleep(5);
return "task over";
});
new Thread(task, "t1").start();
// System.out.println(task.get(6,TimeUnit.SECONDS));
System.out.println(Thread.currentThread().getName() + "----- To do something else ");
while (true) {
if (task.isDone()) {
System.out.println(task.get());
break;
}else {
System.out.println(" April beats her brother , April bullies her brother !!!");
}
}
}
SUM:Future It is unfriendly to obtain the results , The results can only be obtained by blocking or polling .
️ CompletableFuture
Provides a mechanism similar to the observer pattern , You can inform the listener after the task is completed .

CompletionStage Interface :CompletionStage Represents a stage in the asynchronous computing process , After one stage is completed, you can start another stage . A phase can be triggered by a single phase , It can also be triggered by multiple stages .
establish CompletableFuture Four static methods :
runAsync(Runnable) Static methods , No return value , Use the default thread pool ForkJoinPool.
runAsync(Runnable ,Executor ) Static methods , No return value , Incoming thread pool .
supplyAsync(Supplier<U>) Static methods , Return value again , Use the default thread pool ForkJoinPool.
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(3);
// CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
// CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
// CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName());
// Pause for a few minutes
try {
TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) {
e.printStackTrace(); }
return "hello world";
},pool);
// });
System.out.println(future.get());
}
Code demonstration :
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(3);
try {
CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName() + "---- come in");
Integer result = ThreadLocalRandom.current().nextInt(10);
if (result>5){
Integer num =result/0;
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
return result;
}, pool).whenComplete((v, e) -> {
if (Objects.isNull(e)) {
System.out.println("----- The calculation is complete , Update system updateValue: " + v);
}
}).exceptionally((e) -> {
e.printStackTrace();
System.out.println(" Abnormal situation :" + e.getCause() + "\t" + e.getMessage());
return null;
});
System.out.println(Thread.currentThread().getName() + " The thread is busy with other tasks first !");
}catch (Exception e){
e.printStackTrace();
}finally {
pool.shutdown();
}
}
- After the asynchronous task ends , Methods that call back an object automatically .
- The main thread has set the callback , No longer care about the execution of asynchronous threads , Asynchronous tasks can be executed sequentially .
- When an asynchronous task makes an error , Methods that call back an object automatically .

List :
public class CompletableFutureMallDemo {
static List<NetMall> list = Arrays.asList(
new NetMall("jd"),
new NetMall("dangdang"),
new NetMall("pdd")
);
/** * setup by setup * @param list * @param name * @return */
static List<String> getPrice(List<NetMall> list,String name){
return list.stream().map(netMall ->
String.format(name+" in %s price is %.2f",netMall.getName(),netMall.calcPrice(name))
).collect(Collectors.toList());
}
/** * List<NetMall> ==== List<CompletableFuture<String>> ==== List<String> * * @param list * @param name * @return */
static List<String> getPriceByCompletableFuture(List<NetMall> list,String name){
return list.stream().map(netMall -> CompletableFuture.supplyAsync(()->
String.format(name+" in %s price is %.2f",netMall.getName(),netMall.calcPrice(name))
)).collect(Collectors.toList()).stream().map(s->s.join())
.collect(Collectors.toList());
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
List<String> mysql = getPrice(list, "mysql");
mysql.forEach(System.out::println);
long end = System.currentTimeMillis();
System.out.println(" Time consuming :"+(end-start));
System.out.println("========================");
long start2 = System.currentTimeMillis();
List<String> mysql2 = getPriceByCompletableFuture(list, "mysql");
mysql2.forEach(System.out::println);
long end2 = System.currentTimeMillis();
System.out.println(" Time consuming :"+(end2-start2));
}
}
class NetMall{
private String name;
public String getName() {
return name;
}
public NetMall(String name){
this.name=name;
}
public double calcPrice(String name){
try {
TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) {
e.printStackTrace(); }
return ThreadLocalRandom.current().nextDouble()*2+name.charAt(0);
}
}
Common methods :
- Get results and trigger budgets
To get the results :
get()get(long,TImeUtin)join()getNow(T), If the calculation is completed, the result after the calculation is returned , If the calculation is not completed, the default result is returned .
Trigger budget :complete(T), Whether to interruptget()Method immediately returns the value in parentheses .
- Process the calculation results
thenApply, The calculation results are dependent , Two threads are serialized , If there is an exception in the current step, the downward cloud will not continue .handle, This method is normally executed in the same way as the above method , If an exception occurs, you can continue to execute downward .
- Calculate the result for consumption
thenRun, After executionAMission , performBMission , AndBThe task does not requireAResults of the task .thenAccept,BThe task requiresAResults of task execution completion , But no return value .thenApply,BThe task requiresAResults of task execution completion , But there is a return value .
thenRunVSthenRunAsync
- No custom thread pool passed in , The default thread pool is used .
- If you pass in a custom thread pool ,
thenRunMethod executes the second task using the same thread pool as the first task .thenRunAsyncWhen performing the second task , If the thread pool of the first task passed in is customized , The second task uses the default thread poolForkJoinPool. - The system processes too fast , System optimization principle , Then use
mainThreads .
- Choose speed calculation
applyToEither Compare .
- Consolidate the calculation results
thenCombine Process the two results , The first thing to finish is to wait , Wait for other tasks to complete .
️ Thread lock related knowledge
️ Pessimistic lock and optimistic lock
Pessimistic locking :synchronized Key words and lock All implementations of are pessimistic locks . When you think you're using data , There must be another thread to modify the data , Therefore, it will lock the data first , Make sure the data is not modified by other threads .
Use scenarios , Locking first can ensure that when writing , The data is correct .
Optimism lock :
Think you're using data , There will be no other thread to modify data and resources , So no locks will be added . stay java By using lock free programming to achieve , Just judge when updating data , Has any other thread updated this data before .
Rule of judgement :
- Version number mechanism ,
version - The longest used is
CASAlgorithm ,javaThe increment of atomic classes in is throughCASTo achieve .
It is suitable for scenarios with more reading operations , The feature of not locking can greatly improve the performance of its read operation .
synchronized Key words :
If there are more than one object
synchronizedMethods , At a certain moment , As long as the thread calls one of themsynchronizedMethod , Other threads can only wait , In other words , At some point , Only one thread can access thesesynchronizedMethod . The lock is the current objectthis, After being locked , No other thread can enter other threads of the current objectsynchronizedMethod .After adding a common method, it is found that it has nothing to do with the synchronization lock , After changing to two objects , It's not the same lock , The situation immediately changed
Change to static synchronization method , Three
synchronizedThere are some differences in the contents of locks for common methods , The current instance object is locked , Usually refers tothisFor static methods , The lock is of the current classclassobject , For synchronization method blocks , LockedsynchronizedObjects in brackets .When a thread tries to access a synchronized block of code , He must first get the lock , You must release the lock when you exit normally or throw an exception .
All common synchronization methods use the same lock —— Instance object itself , NamelynewThe instance object itself , This categorythisThat is, if a common synchronization method of a real column object acquires a lock , Other normal synchronization methods of the instance object must wait for the method that acquires the lock to be released before acquiring the lock . All static synchronization methods use the same lock —— Class object itself , Concrete instance objectthisThe first mock exam templateclass, These two locks correspond to different objects , Therefore, there is no competition between static synchronization methods and ordinary synchronization methods , But once the static method acquires the lock , Other static methods must wait for the method to release the lock before acquiring the lock .
effect :
- Lock the current instance , Obtain the lock for the current instance before entering the synchronized code .
- Lock the object configured in brackets .
- Lock the current class , Get the lock of the current class before entering the synchronization code .
️ Fair lock and unfair lock
Not fair lock : Unfair locks make better use of cpu Time slice of . Try to reduce cpu In my spare time . Reduces thread overhead .
Reentrant lock : Also called recursive lock , Multiple processes of a thread can acquire the same lock , Hold this lock to re-enter . You can get your own internal lock . Refers to a lock that can be repeatedly and recursively called , After using the lock on the outer layer , The inner layer can still be used , And there are no deadlocks , Such locks are called reentrant locks .
Simply speaking , In a synchronized Modified methods or other methods that internally call this class in the code block synchronized Decorated method or code block , You can always get a lock .
Implicit lock —— synchronized keyword
Display lock —— Lock Also have ReentrantLock This kind of re-entry lock
Deadlock command troubleshooting :
jsp -lView process numberjstack Process numberTroubleshoot problemsjconsoleGraphic tool

️ Interrupt mechanism
Generally speaking, a thread should not be interrupted or stopped by other threads , Instead, the thread should stop itself .
️ LockSupport
Is a thread blocking tool class , All methods are static . among park() Methods and unpark() Method , They are blocking threads and releasing threads . Each thread that uses it has a license , There is only one at most and it will not accumulate .
️ jMM Model
java The specification attempts to define a memory model (Java Memory Model), To shield memory access differences between various hardware and operating systems , The implemented java Consistent access effect can be achieved under all platforms .
JMM Model , Itself is an abstract concept , It doesn't really exist , He only describes a set of conventions or norms . Through this set of specifications , Defines the ( Especially multithreading ), How to read, write, and access variables . It also determines when and how one thread writes to shared variables and how to program visibility to another thread , The key technical points are all around multithreading Atomicity and visibility as well as Orderliness In the .
summary :
The variables we define are stored in physical memory , Each thread has its own working memory . It stores a copy of the variables used by the thread .
️ volatile
Use volatile Decorate shared variables , The data in the main memory is read every time , Then copy it to working memory ,
️ Atomic classes
️ Basic atomic type
Case study :
class MyNumber {
AtomicInteger integer =new AtomicInteger();
public void add(){
integer.getAndIncrement();
}
}
public class AtomicIntegerDemo {
public static final int SIZE = 50;
public static void main(String[] args) throws InterruptedException {
MyNumber number = new MyNumber();
CountDownLatch latch = new CountDownLatch(SIZE);
for (int i = 0; i < SIZE; i++) {
new Thread(() -> {
try {
for (int j = 0; j < 1000; j++) {
number.add();
}
}finally {
latch.countDown();
}
}).start();
}
// Wait for the above 50 threads to complete the calculation . Then go to get the value of the final result
// Thread.sleep(2);
latch.await();
System.out.println(Thread.currentThread().getName()+"\t"+"result: "+number.integer.get());
}
}
️ Atomic class of object attribute modification
Case study :
class MyVar {
public volatile Boolean isInit = Boolean.FALSE;
AtomicReferenceFieldUpdater<MyVar, Boolean> updater = AtomicReferenceFieldUpdater.newUpdater(MyVar.class, Boolean.class, "isInit");
public void init(MyVar myVar) {
if (updater.compareAndSet(myVar, Boolean.FALSE, Boolean.TRUE)) {
System.out.println(Thread.currentThread().getName() + "\t" + "------ start");
try {
Thread.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "\t" + "------ over");
} else {
System.out.println(Thread.currentThread().getName() + "\t" + "------ There is already a thread for initialization !");
}
}
}
/** * @author: yueLQ * @date: 2022-06-30 11:57 */
public class AtomicReferenceFieldUpdateDemo {
public static void main(String[] args) {
MyVar myVar = new MyVar();
for (int i = 0; i < 5; i++) {
new Thread(() -> {
myVar.init(myVar);
}, String.valueOf(i)).start();
}
}
}
边栏推荐
- [linear DP] longest common subsequence
- Completely solve the lost connection to MySQL server at 'reading initial communication packet
- Od modify DLL and exe pop-up contents [OllyDbg]
- Multithreaded printing
- Elk elegant management server log
- Poj-3486-computers[dynamic planning]
- Restcloud ETL WebService data synchronization to local
- Complete training and verification of a neural network based on pytorch
- An article explaining the publisher subscriber model and the observer model
- Classic programming problem: finding the number of daffodils
猜你喜欢
![[QT] add knowledge supplement of third-party database](/img/ea/ca8b07ad80485208f2bb8ee8a78a28.png)
[QT] add knowledge supplement of third-party database

XXL job User Guide

Huawei operator level router configuration example | configuration optionA mode cross domain LDP VPLS example
![[linear DP] shortest editing distance](/img/2f/9a6f661bf478fdd5d53e5a03d7297d.jpg)
[linear DP] shortest editing distance

CX5120控制汇川IS620N伺服报错E15解决方案
![[linear DP] longest common subsequence](/img/47/c3172422e997009facbada929adb1a.jpg)
[linear DP] longest common subsequence

VMware vSphere 6.7 virtualization cloud management 12. Vcsa6.7 update vCenter server license

EtherCAT简介
![[machine learning] vectorized computing -- a must on the way of machine learning](/img/3f/d672bb254f845ea705b3a0ca10ee19.png)
[machine learning] vectorized computing -- a must on the way of machine learning
![[applet project development -- Jingdong Mall] classified navigation area of uni app](/img/cb/b0b79444dc90980cd2220ff9e68549.png)
[applet project development -- Jingdong Mall] classified navigation area of uni app
随机推荐
How to determine the progress bar loaded in the loading interface when opening the game
JS to find duplicate elements in two arrays
Summary of problems encountered in debugging positioning and navigation
Chapter 03_ User and authority management
[linear DP] shortest editing distance
Mybati SQL statement printing
[machine learning] vectorized computing -- a must on the way of machine learning
[applet project development -- JD mall] uni app commodity classification page (Part 2)
UE4 rendering pipeline learning notes
Mouse over effect V
【小程序项目开发 -- 京东商城】uni-app 商品分类页面(下)
Elk elegant management server log
Best used trust automation script (shell)
Cloud native annual technology inventory is released! Ride the wind and waves at the right time
js 找出两个数组中的重复元素
Install vcenter6.7 [vcsa6.7 (vCenter server appliance 6.7)]
xxl-job使用指南
Basic concepts of database
Golang多图生成gif
如何校验两个文件内容是否相同