Java Multithread (java.Thread)
Multithreading
[external link image transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-awkyhfuh-1662909284399) (C: \ users \ Donghua \ appdata \ roaming \ typora \ typera user images \ image-20220907221944898. PNG)]
[external link image transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-9phwkvg3-1662909284400) (C: \ users \ Donghua \ appdata \ roaming \ typora \ typera user images \ image-2022090722117478. PNG)]
[Process and Thread]
- Speaking of the process, I have to talk about the procedure. A program is an ordered collection of instructions and data. It has no running meaning and is a static concept.
- The process is a process of executing a program, which is a dynamic concept. It is the unit of system resource allocation
- Usually, a process can contain several threads. Of course, there must be at least one thread in a process. Otherwise, there is no sense of existence. Thread is the unit of CPU scheduling and execution.
Note: many multithreads are simulated. Real multithreading refers to having multiple CPUs, that is, multiple cores, such as servers. If it is a simulated multithreading, that is, in the case of a cpu, the cpu can only execute one code at the same point in time. Because the switching is fast, there is an illusion of simultaneous execution.
[core concepts of this chapter]
- Threads are independent execution paths;
- When the program is running, even if there is no thread created by itself, there will be multiple threads in the background, such as the main thread and gc thread;
- main() is called the main thread, which is the entry of the system and used to execute the whole program;
- In a process, if more than one thread is opened, the running of the thread is scheduled by the scheduler, which is closely related to the operating system, and the sequence can not be interfered with artificially.
- When operating on the same resource, there will be a problem of resource grabbing, and concurrency control needs to be added;
- Threads 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 inconsistent data
Thread creation
[external link image transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-zm2injj6-1662909284400) (C: \ users \ Donghua \ appdata \ roaming \ typora \ typera user images \ image-2022090723009220. PNG)]
1 Inherit Thread class
- Custom Thread class inherits Thread class
- Rewrite the * * run() * * method and write the thread executor
- Create a thread object and call the * * start() * * method to start the thread
package thread; //The first way to create a thread is to rewrite the run() method and call start to start the thread public class TextThreade extends Thread{ @Override public void run() { //run method for (int i = 0; i < 20; i++) { System.out.println("I'm learning code"+i); } } //Main method, main thread public static void main(String[] args) { //Create a thread object and call the start method to start multiple threads TextThreade textThreade = new TextThreade(); textThreade.start(); for (int i = 0; i < 20; i++) { System.out.println("I'm writing multithreading"+i); } } } //Multiple threads execute alternately at the same time. Note that the thread is not necessarily executed immediately after it is started. It is scheduled by the CPU
II Implement Runnable interface
- Define MyRunnable class and implement Runnable interface
- Rewrite the run() method and write the thread executor
- Create a thread object and call the start() method to start the thread
Runnable objects are recommended because of the limitations of Java single inheritance
package thread; //The second way to create a thread is to implement the runnable interface and rewrite the run () method. The executing thread needs to throw 2 into the runnable interface implementation class and call the start() method public class TextThread2 implements Runnable{ @Override public void run() { //run method for (int i = 0; i < 20; i++) { System.out.println("I'm learning code"+i); } } //Main method, main thread public static void main(String[] args) { //Create runnable interface implementation object TextThread2 textThread2 = new TextThread2(); //Create a thread object, open our thread and proxy through the thread object Thread thread =new Thread(textThread2); thread.start(); //new Thread(textThread2).start(); Abbreviation for (int i = 0; i < 20; i++) { System.out.println("I'm writing multithreading"+i); } } }
Summary
Inherit Thread class
1. The subclass inherits the Thread class and has multi threading capability
2. Start thread: subclass object start()
3. Not recommended: avoid the limitation of OOP single inheritance
Implement Runnable interface
1. The implementation interface Runnable has multithreading capability
2. Start Thread: pass in the target object + Thread object. start()
3. Recommended: avoid the limitation of single inheritance, be flexible and convenient, and facilitate the same object to be used by multiple threads
Initial understanding of concurrency
Tortoise rabbit race case
package thread; import java.util.concurrent.Callable.*; //Simulated tortoise rabbit race public class Race implements Runnable{ //winner private static String winner; @Override public void run() { for (int i = 0; i <= 100; i++) { //Simulated rabbit rest if (Thread.currentThread().getName().equals("rabbit")&& i%10 == 0){ try { Thread.sleep(10); } catch (InterruptedException e){ e.printStackTrace(); } } //Judge whether the game is over boolean flag = gameOver(i); System.out.println(Thread.currentThread().getName()+"Run away"+i+"step"); if (flag=true) {break;} } } //Judge whether the competition is completed private boolean gameOver(int steps){ //Judge whether there is a winner if (winner!=null){ //Game over return true; }{ if (steps>=100) { winner = Thread.currentThread().getName(); System.out.println("winner is "+winner); return true; } } return false; } public static void main(String[] args) { Race race = new Race(); new Thread(race,"rabbit").start(); new Thread(race,"tortoise").start(); } }S
ic static void main(String[] args) {
Race race = new Race();
new Thread(race, "rabbit"). start();
new Thread(race, "Tortoise"). start();
}
}S