当前位置:网站首页>Concurrent programming -- what is threading?
Concurrent programming -- what is threading?
2022-06-13 05:47:00 【Coffee is not bitter**】
List of articles
One 、 What is thread ?
1) Introduce
Threads are scheduling CPU The smallest unit of resources , The thread model is divided into KLT Model and ULT Model ,JVM The use of KLT model
type ,Java Threads and OS Thread persistence 1:1 The mapping relation of , That is to say, there is a java Threads also have a corresponding thread in the operating system .
2)Java Threads and OS Thread persistence 1:1 The mapping relation of
Let's execute the code locally to test whether it is 1:1 The relationship between . The initial system running thread is 1771 individual . We create one with 300 A thread test , See what it turns out to be
public static void main(String[] args) {
for (int i = 0; i < 300; i++) {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}


We can find that from 2018 It's changed to 2351, Ignore slight thread changes , Can see 300 Just one change of , Because the system also runs various threads of other processes .
Two 、 Three ways to create threads
1)extends Thread
① demo example
public class CreateThreadTest1 extends Thread{
@Override
public void run() {
System.out.println(" By inheritance Thread, Thread number :" + currentThread().getName());
}
}
public static void main(String[] args) {
Thread thread = new CreateThreadTest1();
thread.start();
}
② Process description
2)implements Runnable
① demo example
public class CreateThreadTest implements Runnable{
@Override
public void run() {
System.out.println(" By implementing Runnable, Thread number :" + Thread.currentThread().getName());
}
}
public static void main(String[] args) {
Thread thread = new Thread(new CreateThreadTest());
thread.start();
}
② Process description
3)implements Callable
① demo example
public class CreateThreadTest2 implements Callable {
@Override
public Object call() throws Exception {
System.out.println(" By implementing Callable, There is a return value ; Thread number :" + Thread.currentThread().getName());
return 10;
}
}
public static void main(String[] args) {
FutureTask futureTask=new FutureTask(new CreateThreadTest2());
Thread thread = new Thread(futureTask);
thread.start();
try {
System.out.println(futureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
② Process description
- 1. Realization Callable class , rewrite call() Method , The call() Method will act as thread body , And there is a return value .
- 2. establish Callable Instance of implementation class , Use FutureTask Class to packaging Callable object , The FutureTask Object encapsulates the Callable Object's call() Return value of method .
- 3. Use FutureTask Object as Thread Object's target Create and start a new thread .
- 4. call FutureTask Object's get() Method to get the return value after the execution of the child thread
③ Two ways of implementation
- 1. use FutureTask encapsulation
- 2. Thread pool calls
public static void main(String[] args) {
// Create a thread pool at will
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future future = executorService.submit(new CreateThreadTest2());
try {
// Get value
System.out.println(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
// Close thread pool
executorService.shutdown();
}
3、 ... and 、 Three advantages and disadvantages of creating threads
1) Adopt inheritance Thread Class mode :
(1) advantage : Write simple , If you need to access the current thread , No need to use Thread.currentThread() Method , Use it directly this, To get the current thread .
(2) shortcoming : Because the thread class has inherited Thread class , So you can no longer inherit other parent classes .
2) Implemented using Runnable The interface way :
(1) advantage : The thread class just implements Runable Interface , You can also inherit other classes . In this way , Multiple threads can share the same target object , So it is very suitable for multiple threads to handle the same resource , So that we can put CPU Separate code from data , Form a clear model , It better embodies the idea of object-oriented .
(2) shortcoming : Programming is a little more complicated , If you need to access the current thread , You have to use Thread.currentThread() Method .
3)Runnable and Callable The difference between :
(1)Callable The prescribed method is call(),Runnable The prescribed method is run().
(2)Callable After the task is executed, it can return the value , and Runnable The task is not worth returning
(3)call Methods can throw exceptions ,run Method can not , because run The method itself does not throw an exception , So the custom thread class is rewriting run You can't throw an exception when
(4) function Callable The mission can get a Future object , Represents the result of an asynchronous calculation . It provides a way to check if the calculation is complete , To wait for the calculation to complete , And retrieve the calculated results . adopt Future Object can understand task execution , The execution of the task can be cancelled , You can also get execution results .
Four 、 Life state
1) state
- NEW, newly build
- RUNNABLE, function
- BLOCKED, Blocking
- WAITING, wait for
- TIMED_WAITING, Overtime waiting
- TERMINATED,
2) State switching diagram

3) Source location
stay Thread In class , There is an inner class state, To indicate the status
public enum State {
}
5、 ... and 、 Some common state transition method calls
1) from NEW To RUNNABLE The process of
RUNNABLE It can be divided into two stages : Ready state and running state
① call thread.run() To ready state
② call thread.start() Running state
③ call thread.yield() Method from running state to ready state
public static native void yield();
1、 This is a static method , Once executed , It causes the current thread to give up CPU. But should pay attention to , Give up CPU It does not mean that the current thread does not execute , The current thread is yielding CPU after , There will be CPU Competition for resources , But whether it can be assigned again is not certain .
therefore , about Thread.yield() The call to is like saying :“ I've done some of the most important work , I can have a rest , You can give other threads some jobs ”.
2、 Because they will rob again , So it's like I let the opportunity go , If other threads don't cherish them, it's none of my business .
3、yield Only threads with the same or higher priority will be conceded , This is the social rule .
// set priority :MIN_PRIORITY Lowest priority 1;NORM_PRIORITY Normal priority 5;MAX_PRIORITY Highest priority 10
threadA.setPriority(Thread.MIN_PRIORITY);
threadB.setPriority(Thread.MAX_PRIORITY);
4、 Just give up CPU resources , But if you hold a lock , Will not give up . So again AQS Common in , Because it is an optimistic lock .
2) from RUNNABLE To WATING state
① LockSupport.park()
LockSupport Class is Java6(JSR166-JUC) A class introduced , Provides basic thread synchronization primitives .LockSupport It's actually called Unsafe Functions in class , attribute to Unsafe in , There are only two functions :
public native void unpark(Thread jthread);
public native void park(boolean isAbsolute, long time);
边栏推荐
- Mongodb Multi - field Aggregation group by
- Django uploads local binaries to the database filefield field
- Standard input dialog for pyqt5 qinputdialog
- Web site learning and sorting
- Difference between deviation and variance in deep learning
- How MySQL optimizes the use of joint index ABC
- Application virtual directory static resource configuration on tongweb
- August 15, 2021 another week
- Solutions to conflicts between xampp and VMware port 443
- JS output uincode code
猜你喜欢

ffmpeg 下载后缀为.m3u8的视频文件

890. Find and Replace Pattern

MongoDB 多字段聚合Group by

OpenGL馬賽克(八)

AUTOSAR actual combat tutorial pdf version

MySQL performs an inner join on query. The query result is incorrect because the associated fields have different field types.

Agile conflicts and benefits

Misunderstanding of tongweb due to ease of use

Problems encountered in the use of PgSQL

2021.9.30 learning log -postman
随机推荐
Getclassloader() returns null, getclassloader() gets null
How slow is the application system on tongweb? How dead is it?
计算两个时间相差的天数(支持跨月、跨年)
Find out the missing numbers from the natural numbers arranged in order from 0 to 100, and the solution provides
Mongodb multi field aggregation group by
Implementation of concurrent programming locking
15 inclusivegateway and eventgateway of flowable gateway
Solve the problem of garbled code in the MySQL execution SQL script database in docker (no need to rebuild the container)
Quartz basic use
MySQL main query and sub query
How to Algorithm Evaluation Methods
Shell instance
Three paradigms of MySQL
= = relation between int and integer
Calculate the number of days between two times (supports cross month and cross year)
Browser screenshot method (long screenshot, node screenshot, designated area screenshot)
Validation set: ‘flowable-executable-process‘ | Problem: ‘flowable-servicetask-missing-implementatio
Django uses redis to store sessions starting from 0
Vagrant virtual machine installation, disk expansion and LAN access tutorial
Randomly fetch data from the list