Detailed explanation of Java multithreading
Thread introduction
Thread implementation (key)
Thread state
Thread synchronization (key)
Thread communication problem
Advanced topics
Multitasking
- In reality, there are too many examples of doing common things at the same time. It seems that more than a dozen tasks are being done. In fact, our brain still does one thing at the same time.
Multithreading
-
It turned out to be a road. Slowly, because there are too many cars, the road is blocked and the efficiency is very low.
In order to make full use of the efficiency of question number use, multiple lanes are added.
From then on, my mother never used it again, but the road was blocked.
-
Tell me about your multithreading examples (life, games, programming)
Common method call multithreading
Program. Process. Thread
Process and Thread
-
Speaking of the process, I have to say the procedure. Program is an ordered collection of instructions and data. It has no running meaning. It is a static concept.
-
The process is an execution process of the execution program. It is a dynamic concept and the unit of system resource allocation.
-
Usually, several threads can be replaced in a process. Of course, there is at least one thread in a process, otherwise it has no meaning. Thread is the unit of CPU scheduling and execution.
-
Note: many multithreads are simulated. Real multithreading refers to having multiple CPUs, i.e. multiple cores, such as servers. If it is a simulated multithreading, that is, in the case of a CPU, at the same point in time, the CPU can only execute one code. Because the switching is fast, there is the illusion of simultaneous execution.
Core concepts of this chapter
- Threads are independent execution paths;
- When the program is running, even if it does not create its own thread, there will be multiple threads in the background, such as main thread and gc thread;
- main() is called the main thread, which is the entry of the bit system and is used to execute the whole program;
- In a process, if multiple threads are opened up, the running scheduler of threads arranges scheduling. The scheduler is closely related to the operating system, and the sequence can not be interfered by human beings.
- When operating on the same resource, there will be a problem of resource grabbing, and concurrency control needs to be added;
- Threads will bring additional overhead, such as CPU scheduling time and concurrency control overhead.
- Each thread interacts in its own working memory. Improper memory control will cause data inconsistency.
Thread creation
Thread,Runnable,Callable
Three creation methods
Thread
(learning tips: View JDK help documents)
- The custom Thread class inherits the Thread class
- Rewrite the run() method to write the thread executor
- Create a thread object and call the start() method to start the thread
package com.xiancheng.demo01; //Common threading method 1: inherit the Thread class, rewrite the run() method, and call start() to start the Thread public class TestThread1 extends Thread{ @Override public void run() { //run method thread body for (int i = 0; i < 20; i++) { System.out.println("I'm looking at the code---"+i); } } public static void main(String[] args) { //main thread //Create a thread object TestThread1 testThread1 = new TestThread1(); //Call the start() method to start the current thread testThread1.start(); for (int i = 0; i < 20; i++) { System.out.println("I'm learning multithreading--"+i); } } }
- Summary: note that thread clearing is not necessarily executed immediately, but is scheduled by the CPU
Case: download pictures
package com.xiancheng.demo01; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.net.URL; //Contact TestThread to realize multi-threaded synchronous downloading of pictures public class TestThread2 extends Thread{ private String url;//Network picture address private String name;//Save file name public TestThread2(String url,String name){ this.url = url; this.name = name; } @Override public void run() { WebDownloader webDownloader = new WebDownloader(); webDownloader.downloader(url,name); System.out.println("Downloaded a file named:"+name); } public static void main(String[] args){ TestThread2 testThread1 = new TestThread2("https://imgoss.douyucdn.cn/bj/yuba/default/2019/12/20/201912200221045779841615885.jpg","1.jpg"); TestThread2 testThread2 = new TestThread2("https://imgoss.douyucdn.cn/bj/yuba/default/2021/03/26/202103262200428765268485985.jpg","2.jpg"); TestThread2 testThread3 = new TestThread2("https://img.douyucdn.cn/data/yuba/default/2019/08/18/201908182138163129577786480.200x0.jpg","3.jpg"); testThread1.start(); testThread2.start(); testThread3.start(); } } //Downloader class WebDownloader{ //Download method public void downloader(String url, String name){ try { FileUtils.copyURLToFile(new URL(url),new File(name)); } catch (IOException e) { e.printStackTrace(); System.out.println("IO Abnormal, downloader There is a problem with the method"); } } }
- Threads execute simultaneously
Implement Runnable
- Define the MyRunable class to implement the Runable interface
- Implement the run() method and write the thread execution body
- Create a thread object and call the start() method to start the thread
package com.xiancheng.demo01; //Thread creation mode 2: implement the runnable method, rewrite the run() method, and call start to start the thread //Summary: note that thread startup does not specify immediate execution, but is scheduled by the CPU public class TestThread3 implements Runnable{ @Override public void run() { //run method thread body for (int i = 0; i < 1000; i++) { System.out.println("I'm looking at the code---"+i); } } public static void main(String[] args) { //Create an implementation class object for the runnable interface TestThread3 testThread3 = new TestThread3(); //Create a thread object and start our thread agent through the thread object //Thread thread = new Thread(testThread3); //thread.start(); //Abbreviation new Thread(testThread3).start(); for (int i = 0; i < 1000; i++) { System.out.println("I'm learning multithreading--"+i); } } }
Using Runna interface to download pictures
package com.xiancheng.demo01; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.net.URL; //Practice TestThread to download pictures synchronously through multiple threads public class TestThread2 implements Runnable{ private String url;//Network picture address private String name;//Save file name public TestThread2(String url,String name){ this.url = url; this.name = name; } @Override public void run() { WebDownloader webDownloader = new WebDownloader(); webDownloader.downloader(url,name); System.out.println("Downloaded a file named:"+name); } public static void main(String[] args){ TestThread2 testThread1 = new TestThread2("https://imgoss.douyucdn.cn/bj/yuba/default/2019/12/20/201912200221045779841615885.jpg","1.jpg"); TestThread2 testThread2 = new TestThread2("https://imgoss.douyucdn.cn/bj/yuba/default/2021/03/26/202103262200428765268485985.jpg","2.jpg"); TestThread2 testThread3 = new TestThread2("https://img.douyucdn.cn/data/yuba/default/2019/08/18/201908182138163129577786480.200x0.jpg","3.jpg"); new Thread(testThread1).start(); new Thread(testThread2).start(); new Thread(testThread3).start(); } } //Downloader class WebDownloader{ //Download method public void downloader(String url, String name){ try { FileUtils.copyURLToFile(new URL(url),new File(name)); } catch (IOException e) { e.printStackTrace(); System.out.println("IO Abnormal, downloader There is a problem with the method"); } } }
Summary
-
Inherit Thread class
- The subclass inherits the Thread class and has multithreading capability
- start thread: subclass object. start
- Not recommended: avoid the limitations of OPP single thread inheritance
-
Implement Runnable interface
- The implementation interface Runnale has multithreading capability
- Delivery Thread: pass in target object + Thread object. start()
- Recommended: it avoids the limitation of single inheritance, is flexible and convenient, and is convenient for the same object to be used by multiple threads
)