Java multithreading
Article directory
Part1
concept
- Call between methods: Call of common methods, from where to where, a closed path
- Use of multithreading: opening up multiple paths
Program, process and thread
The program running in the operating system is a Process, such as watching video. A Process can have multiple threads, such as listening to sound, watching images, displaying subtitles and so on
Interesting understanding of threads
-
Process is the smallest unit of resource management, and thread is the smallest unit of program execution.
-
Each process has its own data, code, and stack segments. Thread is a lightweight process, which contains independent stack and CPU register states. Thread is an execution path of the process. Each thread shares all the resources of its affiliated processes, including open files, memory pages, signal identifiers and dynamically allocated memory.
-
Because threads are smaller than processes, threads spend less CPU resources.
-
In operating system design, the main purpose of evolving threads from processes is to better support multiprocessors and reduce the overhead of process context switching.
-
Relationship between thread and process: the thread belongs to the process. The thread runs in the process space. The threads generated by the same process share the same user memory space. When the process exits, all the threads generated by the process will be forced to exit and be cleared. Therefore, a thread cannot execute independently. It must be attached to a running application program (i.e. a process). A process needs at least one thread to execute as its instruction. The process manages resources (such as CPU, memory, files, etc.). The thread is assigned to a CPU for execution.
Difference between thread and process: when the operating system allocates process resources, multiple threads belonging to the same process can share the memory resources in the process with each other, because the thread does not have its own independent memory resources, it only has its own stack and local variables. Among multiple processes, each process has its own set of variables, that is, each process has its own independent memory unit. This makes the communication between multiple threads easier and more efficient than that between multiple processes.
Create thread
- Inherit Thread class
- Implement the Runnable interface
- Implement Callable interface
Inherit Thread class
package cn.chenye.thread; /** * Create thread mode 1 * Inherit Thread, override run method * * @author ASUS * */ public class TestThread extends Thread{ /** * Thread entry point */ @Override public void run() { for(int i=0;i<20;i++) { System.out.println("listening to music "); } //super.run(); } public static <StartThread> void main(String[] args) { //Start thread calls subclass object //Create a subclass object TestThread st=new TestThread(); //Start multithreading st.start();//No immediate call is guaranteed, CPU decides to call and waits for scheduling //st.run(); / / call to a normal method. Multithreading is not enabled for(int i=0;i<20;i++) { System.out.println("while coding "); } } }
Implement the Runnable interface
package cn.chenye.thread; /** * Create thread mode 2 * Create: implement runnable + override run * Start: create implementation class object + thread object + start * @author ASUS * */ public class StartRun implements Runnable{ /** * Thread entry point */ @Override public void run() { for(int i=0;i<20;i++) { System.out.println("listening to music "); } //super.run(); } public static <StartThread> void main(String[] args) { //Start thread to create implementation class object StartRun st=new StartRun(); //Create proxy class object Thread t=new Thread(st); //Start multithreading t.start(); //st.run(); / / call to a normal method. Multithreading is not enabled /**Code anonymity, if an object is used only once new Thread(new StartRun()).start(); */ for(int i=0;i<20;i++) { System.out.println("while coding "); } } }
It is recommended to use this method to avoid the limitation of single inheritance. OOP is multi implementation, flexible and convenient, and it is convenient to unify the agents of objects
Realization of simulated 12306 ticket grabbing
package cn.chenye.thread; /** * Shared resources, concurrent * Need to ensure thread safety * @author ASUS * */ public class Web12306 implements Runnable{ // private int ticketNums=99; @Override public void run() { while(true) { if(ticketNums<0) { break; } System.out.println(Thread.currentThread().getName()+"-->"+ticketNums--); } } //Multiple agents for the same resource public static void main(String[] args) { //A resource Web12306 web=new Web12306(); //Multiple agents new Thread(web,"1").start(); new Thread(web,"2").start(); new Thread(web,"3").start(); } }
Simulated tortoise and rabbit race
package cn.chenye.thread; /** * Simulated tortoise and rabbit race * @author ASUS * */ public class Racer implements Runnable{ private static String winner;//Winner @Override public void run() { for(int step=1;step<=100;step++) { //Simulate rest, set delay if(Thread.currentThread().getName().equals("Rabbit")&&step%10==0) { try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println(Thread.currentThread().getName()+"-->"+step); //Judge whether the game is over boolean flag=gameOver(step); if (flag) { break; } } } private boolean gameOver(int steps) { if(winner!=null) { return true; }else { if(steps==100) { winner=Thread.currentThread().getName(); System.out.println("winner==>"+winner); return true; } return false; } } public static void main(String[] args) { Racer racer=new Racer(); new Thread(racer,"Tortoise").start(); new Thread(racer,"Rabbit").start(); //racer.gameOver(100); } }
Implement Callable interface
Understand that concurrent becomes JUC override call method