当前位置:网站首页>Multithreading and high concurrency (1) -- basic knowledge of threads (implementation, common methods, state)
Multithreading and high concurrency (1) -- basic knowledge of threads (implementation, common methods, state)
2022-04-23 05:49:00 【The green flowers of Wang Li's family】
One 、 Thread implementation
Threads can be implemented in the following ways :
1. Inherit Thread class , rewrite run Method
2. Realization Runnable Interface , rewrite run Method
3.lambda expression
4. adopt Callable and FutureTask Create thread
5. Creating threads through thread pools
Here we only summarize the first three points , The following two points will be summarized in detail in the multithreading section .
I don't say much nonsense , Go straight to the code :
public class GreatThread {
static class MyThread extends Thread {
@Override
public void run() {
System.out.println(" I am the successor Thread from ");
}
}
static class MyRun implements Runnable {
@Override
public void run() {
System.out.println(" I'm realizing Runnable from ");
}
}
public static void main(String[] args) {
new MyThread().start();
new Thread(new MyRun()).start();
new Thread(()->
{
System.out.println(" I am a lambda From the expression ");
}).start();
}
}
The operation results are as follows :
I am the successor Thread from
I'm realizing Runnable from
I am a lambda From the expression
Alibaba code specification prompt : Thread resources are best provided through thread pools , It is not allowed to explicitly create threads in the application .
explain : The advantage of using thread pool is to reduce the time spent on creating and destroying threads and the overhead of system resources , Solve the problem of insufficient resources . If you do not use thread pools , It may cause the system to create a large number of similar threads, leading to memory consumption or “ Over switching ” The problem of .
lambda The expression states :
Basic grammar :
(parameters) -> expression// expression
or
(parameters) ->{
statements; }// Code declaration
Common examples :
// 1. No parameters required , The return value is 5
() -> 5
// 2. Receive a parameter ( Numeric type ), Back to its 2 Times value
x -> 2 * x
// 3. Accept 2 Parameters ( Numbers ), And return their difference
(x, y) -> x – y
// 4. receive 2 individual int Type integer , Back to their and
(int x, int y) -> x + y
// 5. Accept one string object , And print on the console , No value returned ( Looks like a return void)
(String s) -> System.out.print(s)
In conclusion, we can see that ,lambda Expressions implement multithreading and Runnable The interface is essentially the same .
And we'll see Thread Source code :
public class Thread implements Runnable {
}
Thread Also realize Runnable Interface to implement thread .
Two 、 State of thread
The status of the thread can refer to : The life cycle of a thread
establish (new)
be ready (runnable)
function (running)
Blocking (blocked)
Death (terminated
Here I will draw the running diagram of thread in detail in combination with common methods , As shown in the figure :

3、 ... and 、 Common methods of thread analysis
1、Thread The basic method
// Get the currently running thread
Thread thread = Thread.currentThread();
// Thread name
String name = thread.getName();
// Threads id
long id = thread.getId();
// Thread priority
int priority = thread.getPriority();
// Survival
boolean alive = thread.isAlive();
// Whether to guard threads
boolean daemon = thread.isDaemon();
2、start() And run()
// Start a new thread
public synchronized void start();
// Thread method body , It has nothing to do with starting the thread
public void run();
start(): Start a thread , There is no order between threads , Is in accordance with the CPU The allocated time slice switches back and forth .
run(): Calling thread's run Method , It's a normal method call .
public static void main(String[] args) {
new Thread(()-> {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "A").start();
new Thread(()-> {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "B").start();
}
The output is as follows :
A 0
B 0
B 1
A 1
A 2
B 2
B 3
A 3
B 4
A 4
It can be seen that , There is no order between threads .
3、sleep() Method
sleep(): Sleep at a specified time , When the time is up, the code will continue to execute , If you need to wake up before the time is up, you need to use interrupt() To wake up at any time . If the current thread enters the synchronization lock ,sleep Method does not release the lock . Even if the current thread gives up cpu Permission to use , But other threads blocked by synchronization lock cannot get execution .
Source code :
public static native void sleep(long millis) throws InterruptedException;
public static void sleep(long millis, int nanos)
throws InterruptedException {
}
The test code is as follows :
static class MyThread extends Thread {
@Override
public void run() {
try {
System.out.println(new Date() + "\t"+" I am the successor Thread from , I'll pause first 20 second ");
Thread.sleep(20000);
} catch (InterruptedException e) {
System.out.println(new Date() + "\t"+" I am the successor Thread from , I can't pause ");
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread myThread = new MyThread();
// Threads 1
myThread.start();
//main The main thread sleep, Prevent subsequent threads 2 And thread 1 Cross execution
Thread.sleep(2000);
// Threads 2
new Thread(()-> {
System.out.println(new Date() + "\t" +" Don't let you pause ");
// You can call... Without acquiring a lock interrupt
myThread.interrupt();
}).start();
}
The operation results are as follows :
Fri Nov 26 15:20:18 CST 2021 I am the successor Thread from , I'll pause first 20 second
Fri Nov 26 15:20:20 CST 2021 Don't let you pause
Fri Nov 26 15:20:20 CST 2021 I am the successor Thread from , I can't pause
4、yield() Method
call yield Method causes the current thread to hand over CPU jurisdiction , Give Way CPU To execute other threads . Give up cpu It doesn't mean that the current thread doesn't execute . Current thread yield cpu after , There will be cpu Competition for resources , But can it be reassigned to , Not necessarily .
static class MyThread extends Thread {
@Override
public void run() {
long beginTime = System.currentTimeMillis();
int count = 0;
for (int i = 0; i < 100000; i++) {
count = count + (i + 1);
Thread.yield();
}
long endTime = System.currentTimeMillis();
System.out.println(" when :" + (endTime - beginTime) + "(ms)");
}
}
public static void main(String[] args) throws InterruptedException {
Thread myThread = new MyThread();
// Threads 1
myThread.start();
}
Thread.yield(); Uncommented , when 56ms, Comment out , when 2ms.
5、wait() and notify()
wait、notify and notifyAll The method is Object Class final native Method . Can't be overridden by subclass .
public final void wait() throws InterruptedException;
public final native void wait(long timeout) throws InterruptedException;
public final void wait(long timeout, int nanos) throws InterruptedException;
public final native void notify();
public final native void notifyAll();
wait() Method must be in a method decorated with synchronous keywords to call .
wait() The method refers to letting yourself temporarily give up the synchronization lock , So that other threads waiting for this synchronization lock can get the opportunity to execute . Only other methods call notify() perhaps notifyAll() To wake up the relevant thread . call notify perhaps notifyAll Method does not release the lock , But let him participate in the lock competition .
wait() The function of the method is to release the lock , Join the waiting line , When calling interrupt() After the method , The thread must acquire the lock first and then , Then throw an exception InterruptedException.
6、join()
Add the specified thread to the current thread , You can merge two threads that execute alternately into threads that execute sequentially . It's like jumping in the queue , Or just a toilet , You have to wait until I'm finished .
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
// Check that the thread is alive
while (isAlive()) {
// call wait Method
wait(0);
}
} else {
// Check that the thread is alive
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
join() and sleep() equally , Can be interrupted ( When interrupted , Will throw out InterrupptedException abnormal ); The difference is ,join() Internal call wait(), It's a lock , and sleep() Will keep the lock all the time .
7、interrupt()
interrupt() The method is just to change the interrupt state , It does not interrupt a running thread .
As we know from the above , Once the thread passes sleep、wait、 perhaps join Blocking , call interrupt(), Will throw out InterrupptedException abnormal .
public void interrupt() {
if (this != Thread.currentThread())
checkAccess();
synchronized (blockerLock) {
Interruptible b = blocker;
if (b != null) {
// Only change the interrupt state
interrupt0(); // Just to set the interrupt flag
b.interrupt(this);
return;
}
}
interrupt0();
}
isInterrupted(), Used to judge the interrupt status of the current thread (true or false).
interrupted() It's a Thread Of static Method , After getting the interrupt status , Used to restore the interrupt state , Set the interrupt state to false.
static class MyThread extends Thread {
@Override
public void run() {
synchronized (this) {
try {
// Thread gives up lock
wait();
} catch (InterruptedException e) {
// InterruptedException false
System.out.println("InterruptedException\t" + Thread.currentThread().isInterrupted());
}
}
}
}
public static void main(String[] args) {
Thread myThread = new MyThread();
// Threads 1
myThread.start();
// Get interrupt status
boolean interrupted = myThread.isInterrupted();
// interrupted=false
System.out.println("myThread call interrupt Before the method :" + interrupted);
// Change interrupt status
myThread.interrupt();
// Get interrupt status
boolean interrupted2 = myThread.isInterrupted();
// interrupted2=true
System.out.println("myThread call interrupt After the method :" + interrupted2);
// The main thread returns to the interrupted state
boolean interrupted3 = Thread.interrupted();
// interrupted3=false
System.out.println("interrupted() After restoring the interrupted state :" + interrupted3);
}
The output is as follows :
myThread call interrupt Before the method :false
myThread call interrupt After the method :true
interrupted() After restoring the interrupted state :false
InterruptedException false
ps: If a thread is blocked in one Selector selector , Then through the interrupt() When you interrupt it ; The thread's interrupt flag will be set to true, And it will immediately return from the selection operation .
版权声明
本文为[The green flowers of Wang Li's family]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230540317477.html
边栏推荐
猜你喜欢

Ora: 28547 connection to server failed probable Oracle net admin error

JVM series (3) -- memory allocation and recycling strategy

域内用户访问域外samba服务器用户名密码错误

JDBC连接数据库

Batch import of orange single micro service

‘EddiesObservations‘ object has no attribute ‘filled‘

Manually delete registered services on Eureka

Jiugong magic square - the 8th Lanqiao provincial competition - group C (DFS and comparison of all magic square types)

字符串(String)笔记

Radar equipment (greedy)
随机推荐
Character recognition easyocr
JVM series (3) -- memory allocation and recycling strategy
AcWing 836. Merge set (merge set)
多线程与高并发(2)——synchronized用法详解
JDBC操作事务
redhat实现目录下特定文本类型内关键字查找及vim模式下关键字查找
excel获取两列数据的差异数据
第36期《AtCoder Beginner Contest 248 打比赛总结》
AcWing 1096. Detailed notes of Dungeon Master (3D BFS) code
Strategy for improving the conversion rate of independent stations | recovering abandoned users
Jiugong magic square - the 8th Lanqiao provincial competition - group C (DFS and comparison of all magic square types)
What is JSON? First acquaintance with JSON
多线程与高并发(1)——线程的基本知识(实现,常用方法,状态)
Flutter 新一代圖形渲染器 Impeller
Package mall system based on SSM
Common protocols of OSI layer
JS number capitalization method
io. lettuce. core. RedisCommandExecutionException: ERR wrong number of arguments for ‘auth‘ command
Data mining -- understanding data
Flutter 新一代图形渲染器 Impeller