当前位置:网站首页>Interviewer: will concurrent programming practice meet? (detailed explanation of thread control operation)
Interviewer: will concurrent programming practice meet? (detailed explanation of thread control operation)
2022-07-05 21:13:00 【Trouvailless】
Preface
In the use of Java In actual programming , Multithreading can be said to be ubiquitous , It can be used for any concurrent execution , It would be terrible not to use multithreading in an application , therefore It is very important to master the thread and its control operation .
Through this article, I will introduce you to master thread control operation , Thank you for watching .
Catalog
:pencil2:
:pencil2:
One 、 Basic concept of thread
1. Parallel and concurrent
parallel : Multiple CPU The core works at the same time , Dealing with different tasks .
Concurrent : Multiple tasks are used alternately CPU The core work , In order to improve the CPU utilization .
2. Processes and threads
process : An execution of a program . Resources are created and allocated by the operating system , Perform a single task .
Process is an independent unit of resource allocation and scheduling , Each process has its own memory space and system resources . All threads in the process share heap storage space , Save the objects and constant pools defined in the program .
Windows In the system , Each running Java The program is an independent process .
Threads : Execution unit in process , No separate resources are allocated , Perform a single subtask .
Threads are the basic unit of in-process scheduling and dispatch , Share process resources . Each thread has its own independent stack storage space , Save the methods executed by the thread and the basic types of data .
Running Java The program contains at least one main thread main , Users can go to Java Customize and call multiple threads in the program .JVM The garbage collection thread is also a separate thread .
Two 、 Running state of thread
Thread except create state New And end status Terminate Outside , There are mainly the following operating states :
① function (Running) :CPU The thread is executing .
② be ready (Runnable) : Thread is all ready , wait for CPU perform .
function / Ready state They are collectively referred to as operational states Runnable.Java In the program , The thread is in function / Ready state The switch between is made by JVM Automatic scheduling , Developers don't know . The scheduling among threads adopts the multi queue time slice rotation algorithm with sub priority . The process is finished CPU The time slice will save its own state before switching to the ready state , Reload the next time you enter the running state .
③ Blocking (Blocked) : Thread due to lack of other resources , For example, requesting that resources be locked and execution be suspended . Enter the ready state after obtaining resources .
④ wait for (Waitting) : The thread accepted the wait instruction , Release resources and pause execution . Over time / Enter the ready state after receiving the wake-up command .
3、 ... and 、 Thread operation practice
Runnable The interface only declares run Method , from Thread Class implementation . Developers in run Method to define the functions that the runtime thread will perform , The thread is started by Java The virtual machine automatically calls and executes . If the developer actively calls run Method , It will only be executed as a common method .
1. There are two ways to define threads
① Inherit Thread class , rewrite run Method .
public class MyThread extends Thread { @Override
public void run() { System.out.println(Thread.currentThread().getName());
}
}
② Realization Runnable Interface , Realization run Method . Recommended , The limitation of single inheritance is avoided .
public class MyThread implements Runnable { @Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
2. Start thread
Thread Class definition start Method . call start After the method , The system will start a new thread to enter the ready state : from JVM The thread will be automatically scheduled , Call and execute the thread's at run time run Method . A thread can only be started once .
① If the custom thread class inherits Thread class , Direct start .
public class Main { public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread("ThreadName");
t1.start();
t2.start();
}
}
② If the custom thread class implements Runnable Interface , You need to use Thread Class to start the thread .
public class Main { public static void main(String[] args) {
MyThread mythread = new MyThread();
Thread t1 = new Thread(mythread); // The system specifies the default thread name Thread-X
Thread t2 = new Thread(mythread, "ThreadName"); // Developer defined thread name
t1.start();
t2.start();
}
}
3. Define and start threads at the same time
By anonymous inner classes , We can implement a simple way to define and start threads at the same time .
public class Main { public static void main(String[] args) {
Thread thread = new Thread(new Runnable(){ public void run(){
System.out.println(Thread.currentThread().getName());
}
}).start();
}
}class Test { public void method() {
System.out.println(Thread.currentThread().getName());
}
}
4. Thread eject and pause
Thread Class definition yield Method . The current thread executes to Thread.yield()
Method , Will stop running and enter the ready state . But after the thread switches to the ready state , When was it JVM Scheduling back to running status is beyond the control of the developer .
public class ThreadDemo { public static void main(String[] args) {
MyThread mythread = new MyThread();
Thread t1 = new Thread(mythread);
Thread t2 = new Thread(mythread);
t1.start();
t2.start();
} static class MyThread implements Runnable { @Override
public void run() { int count = 0; for (int i = 0; i < 10000; i++) {
Thread.yield(); // Switch to ready state
count++;
System.out.println(count);
}
}
}
}
Thread Class definition sleep Method . The current thread executes to Thread.sleep(1000)
Method , It will stop running and enter the blocking state , But the object lock remains , Other threads cannot access their resources . Enter the ready state after timeout . call sleep Methods need to be captured or thrown InterruptException abnormal .
public class ThreadDemo { public static void main(String[] args) {
MyThread mythread = new MyThread();
Thread t1 = new Thread(mythread);
Thread t2 = new Thread(mythread);
t1.start();
t2.start();
} static class MyThread implements Runnable { @Override
public void run() { int count = 0; for (int i = 0; i < 10000; i++) { try{
Thread.sleep(1000); // The current thread is paused 1s
} catch(InterruptException e){
e.printStackTrace();
}
count++;
System.out.println(count);
}
}
}
}
5. Thread wait and wake
① Thread waiting
Current thread execution obj.wait()
Method , The thread will stop running and release the object lock obj, Other threads can access their resources . At the same time, the thread enters obj Object's waiting pool , Until it is notify Method wakes up to the ready state . call wait Methods need to be captured or thrown InterruptException abnormal .
wait Method allows timed waits . Current thread execution obj.wait(1000)
Method , After the timing ends, the thread will automatically wake up and enter the ready state .
② Thread wake up
Current thread execution obj.notify()
Method , Will randomly from obj Object waits for a thread in the pool to wake up , Make it ready . however notify Method does not release the object lock of the current process , If the thread holds obj The lock of the object , Only after the current thread releases the lock can other threads awakened be executed . If you want to be awakened, the thread executes first ,notify Add after method wait Method release lock .
Current thread execution obj.notifyall()
Method , Will bring all obj Object waits for all threads in the pool to wake up .
public class ThreadDemo { public static void main(String[] args) {
MyThread t = new MyThread("t"); synchronized(t) { // Yes t Set object lock
try {
t.start();
System.out.println("1");
t.wait(); // Current thread release t lock , Get into t Object waiting pool
System.out.println("4");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} static class MyThread extends Thread { @Override
public void run() { synchronized (this) { // Yes t Set object lock
Thread.sleep(1000);
System.out.println("2"); this.notify(); // Wake up one at random t Object waits for threads in the pool
System.out.println("3");
}
}
}
}
6. Thread the interrupt
call t.stop()
Method can force the thread to terminate t function , But forcing thread interrupts can cause unexpected problems , It is not recommended to use .
At present, the method of setting thread interrupt flag is mainly adopted , Send an abort signal to the thread . The thread terminates the run itself :
t.interrupt()t.isInterrupted()t.interrupted()
public class ThreadDemo { public static void main(String[] args) {
MyThread mythread = new MyThread();
Thread t = new Thread(mythread);
t.start(); try {
Thread.sleep(500);
} catch (InterruptedException e) {}
t.interrupt(); // Set the interrupt flag to true
} static class MyThread implements Runnable { @Override
public void run() { while (true) {
System.out.print("hello"); if(this.isInterrupted()){ // Check the interrupt flag , if true End of cycle
break;
}
}
}
}
}
Next, I'll share with you what this document covers : Java、MyBatis、ZooKeeper、Dubbo、Elasticsearch、Memcached、Redis、MySQL、 Spring、Spring Boot、Spring Cloud、RabbitMQ、Kafka、Linux Etc. technology stack , common 1000 Multiple interview questions .
The little companion you need can In the cargo area of official account below
The following is just Java Concurrent programming is a knowledge point
边栏推荐
- 五层网络协议
- Pytorch实战——MNIST数据集手写数字识别
- Binary search
- 2022-07-03-cka- latest feedback from fans
- leetcode:1755. 最接近目标值的子序列和
- R language [data management]
- Add ICO icon to clion MinGW compiled EXE file
- PHP deserialization +md5 collision
- postgis 安装地理信息扩展
- Dictionary tree simple introductory question (actually blue question?)
猜你喜欢
How to send samples when applying for BS 476-7 display? Is it the same as the display??
Wood board ISO 5660-1 heat release rate mapping test
Influence of oscilloscope probe on measurement bandwidth
ArcGIS\QGIS无插件加载(无偏移)MapBox高清影像图
2022-07-03-cka- latest feedback from fans
面试官:并发编程实战会吗?(线程控制操作详解)
Influence of oscilloscope probe on signal source impedance
基于 Ingress Controller 在集群外访问 Zadig 自测环境(最佳实践)
Phpstudy Xiaopi's MySQL Click to start and quickly flash back. It has been solved
显示屏DIN 4102-1 Class B1防火测试要求
随机推荐
Selenium gets the verification code image in DOM
@Validated basic parameter verification, grouping parameter verification and nested parameter verification
2022-07-03-cka- latest feedback from fans
获取前一天的js(时间戳转换)
Opérations de lecture et d'écriture pour easyexcel
启牛2980有没有用?开户安全吗、
MYSQL IFNULL使用功能
让开发效率飞速提升的跨端方案
Material design component - use bottomsheet to show extended content (II)
木板ISO 5660-1 热量释放速率摸底测试
国外LEAD美国简称对照表
MySQL ifnull usage function
postgres 建立连接并删除记录
Is Kai Niu 2980 useful? Is it safe to open an account
Sophomore personal development summary
JS common method encapsulation
示波器探头对测量带宽的影响
Matplotlib drawing retouching (how to form high-quality drawings, such as how to set fonts, etc.)
Why can't Chinese software companies produce products? Abandon the Internet after 00; Open source high-performance API gateway component of station B | weekly email exclusive to VIP members of Menon w
ts 之 类的简介、构造函数和它的this、继承、抽象类、接口