Basic concepts of operating system (Master)
example:
The program keeps outputting a greeting on the screen(Like "hello") "At the same time, when I input fixed input through the keyboard, the program stops outputting greetings to the screen(For example, input gun)
Single thread
package com.cskaoyan._01introduction; import java.util.Scanner; import java.util.concurrent.TimeUnit; /** * @description: **/ /* The program keeps outputting a greeting sentence (such as "hello") on the screen "At the same time, "when I input fixed input through the keyboard, the program stops outputting greetings to the screen (for example, entering gun) */ public class Demo { public static boolean flag = true; public static void main(String[] args) { System.out.println("say hello before"); sayHelloRecycling(); System.out.println("say hello after"); System.out.println("wait stop before"); waitToStop(); System.out.println("wait stop after"); } private static void waitToStop() { Scanner scanner = new Scanner(System.in); while (flag) { String s = scanner.nextLine(); if ("gun".equals(s)) { flag = false; break; } } } private static void sayHelloRecycling() { while (flag) { System.out.println("are you there?"); // Pause try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } } } }
Multithreading
package com.cskaoyan._01introduction; import java.util.Scanner; import java.util.concurrent.TimeUnit; /** * @description: **/ /* The program keeps outputting a greeting sentence (such as "hello") on the screen "At the same time, "when I input fixed input through the keyboard, the program stops outputting greetings to the screen (for example, entering gun) */ public class Demo2 { public static boolean flag = true; public static void main(String[] args) { System.out.println("say hello before"); sayHelloRecycling(); System.out.println("say hello after"); System.out.println("wait stop before"); waitToStop(); System.out.println("wait stop after"); } private static void waitToStop() { new Thread(new Runnable() { @Override public void run() { Scanner scanner = new Scanner(System.in); while (flag) { String s = scanner.nextLine(); if ("gun".equals(s)) { flag = false; break; } } } }).start(); } private static void sayHelloRecycling() { new Thread(new Runnable() { @Override public void run() { while (flag) { System.out.println("are you there?"); // Pause try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } }
process
- The running activity of a computer program on a data set Process is the basic unit of resource scheduling and allocation in operating system
- Simple understanding: a running program or software
thread
- There can be multiple subtasks in a process, and each subtask is a thread From the perspective of execution strength, a thread is an execution path Thread is the basic unit of CPU resource scheduling and allocation
- Thunder download movie
What is the relationship between process and thread
- Threads are process dependent
- A process can have multiple threads
- Threads share resources for processes
serial
- One task after another is executed in sequence
parallel
- At the same time point, multiple tasks are executed simultaneously
Concurrent
- Multiple tasks are executed simultaneously in the same time period
java program operation principle (Master)
Principle of java + main class name
- The java command will create a jvm process
- The jvm process will create a thread, and the main thread is main
- Execute the main method in the main thread
Is the jvm single threaded or multi-threaded
The jvm is multithreaded
- There is 1 main thread
- There is also a garbage collection thread
Implementation mode 1 of multithreading: inherit Thread class (key)
A thread is an execution thread in a program. The Java virtual machine allows applications to run multiple execution threads concurrently
Document example
step
- Define a class and inherit the Thread class
- Override run method
- Create subclass objects
- start()
package com.cskaoyan._02implone; /** * @description: * @author: Sedum * @date: 2022/1/20 10:25 **/ /* 1. Define a class that inherits the Thread class 2. Override run method 3. Create subclass objects 4. start() */ public class Demo1 { public static void main(String[] args) { // 3. Create subclass objects MyThread myThread = new MyThread(); // 4. start() myThread.start(); } } //1. Define a class and inherit the Thread class class MyThread extends Thread{ //2. Rewrite the run method @Override public void run() { System.out.println("The child thread executed!!!"); } }
matters needing attention
-
Executive characteristics
-
Randomness
-
package com.cskaoyan._02implone; /** * @description: **/ /* 1. Define a class that inherits the Thread class 2. Override run method 3. Create subclass objects 4. start() */ public class Demo2 { public static void main(String[] args) { // 3. Create subclass objects MyThread2 myThread = new MyThread2(); MyThread2 myThread2 = new MyThread2(); // 4. start() myThread.start(); myThread2.start(); } } //1. Define a class and inherit the Thread class class MyThread2 extends Thread{ //2. Rewrite the run method @Override public void run() { for (int i = 0; i < 1000; i++) { System.out.println(i); } } }
-
-
What is the difference between the run method and the start method
-
Direct call run Method execution results before 0 1 2 3 4 5 6 7 8 9 after use start Method execution results before after 0 1 2 3 4 5 6 7 8 9
-
The run method does not open up a new execution path at all, but executes in sequence
-
Directly calling the run method is equivalent to calling ordinary member methods
-
The start method is the real way to create a thread
-
Only the code in the run method will be executed in the sub thread. We need to write our code into the run method, and it must be the start method when starting
-
Other methods are used in the run method
-
-
Can the same thread be started multiple times?
- No Java Lang.illegalthreadstateexception an exception will be reported if the same thread is started multiple times
-
Who represents a real thread?
- Only the objects of Thread class and its subclasses represent a Thread
Set / get thread name
String | getName() returns the name of the thread |
---|---|
void | setName(String name) changes the thread name to be the same as the parameter name. |
---|---|
Thread(String name) assigns a new thread object. The thread name can also be set through the construction method |
The default name of the Thread the Thread number
Gets the name of the main thread
static Thread | currentThread() returns a reference to the thread object currently executing |
---|---|
package com.cskaoyan._02implone; /** * @description: Set get thread name **/ public class Demo4 { public static void main(String[] args) { // Gets the name of the main thread Thread thread = Thread.currentThread(); System.out.println("Main thread name = " + thread.getName()); // Create subclass objects MyThread5 t1 = new MyThread5(); MyThread5 t2 = new MyThread5(); // Set thread name // setName(String name) t1.setName("Wang Dao Peng Yuyan"); t2.setName("Wang Dao Wu Yanzu"); // The start method starts t1.start(); t2.start(); } } // Inherit Thread class class MyThread5 extends Thread{ // run method override @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println(getName()+"------"+i); } } }
Thread scheduling (Master)
What is thread scheduling?
The process by which the system allocates CPU resources to threads
classification
- Collaborative thread scheduling
- The execution time of the thread is determined by the thread itself. The thread completes its own work, reports to the system, and switches to other threads
- Preemptive thread scheduling
- The execution time of a thread is not determined by the thread, but by the system Whoever gets it will execute it
What scheduling method is used in java?
Preemptive thread scheduling
Thread priority (understand)
Operating system thread priority
- Static priority fixed value
- Dynamic priority: the priority of executing threads will decrease with the extension of execution time At the same time, the priority of the waiting thread will increase with the extension of the waiting time
- Static priority + dynamic priority
Thread priority in java
static int | MAX_PRIORITY is the highest priority a thread can have. ten |
---|---|
static int | MIN_PRIORITY is the lowest priority a thread can have. one |
static int | NORM_PRIORITY is the default priority assigned to the thread. five |
Set get thread priority
int | getPriority() returns the priority of the thread. |
---|---|
void | setPriority(int newPriority) changes the priority of the thread. |
---|---|
package com.cskaoyan._02implone; /** * @description: thread priority **/ public class Demo5 { public static void main(String[] args) { // Create subclass objects MyThread6 t = new MyThread6(); // | static int | MAX_PRIORITY is the highest priority a thread can have. 10 | //| static int | MIN_PRIORITY is the lowest priority a thread can have. 1 | //| static int | NORM_PRIORITY is the default priority assigned to the thread. 5 | //setPriority(int pri) t.setPriority(Thread.MAX_PRIORITY); // Get thread priority int priority = t.getPriority(); System.out.println("priority = " + priority); // The start method starts t.start(); } } class MyThread6 extends Thread{ // run @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println(i); } } }
Is priority in java useful?
practice:
Requirements:
Create 2 threads, both of which print 10
One thread has the highest priority and the other thread has the lowest priority
start-up
Normal logic analysis: high priority is executed first, and low priority is executed later The number of high priority 10 shall be printed first, and the low priority shall be printed again
Conclusion:
The results of the implementation did not meet our expectations
reason:
The priority in java is only a static priority, just a "suggestion" to the operating system
Operating system: dynamic + static
java official: Thread priority is not completely useless. We use Thread priority, which has statistical significance. Generally speaking, high priority threads
The cpu execution time occupied is a little more. Low priority threads occupy a little less cpu execution time
package com.cskaoyan._02implone; /** * @description: java Is the priority in useful **/ /* Requirements: Create 2 threads, both of which print 10 1 One thread has the highest priority and the other thread has the lowest priority start-up Normal logic analysis: high priority is executed first, and low priority is executed later The number of high priority 10 shall be printed first, and the low priority shall be printed again */ public class Demo6 { public static void main(String[] args) { // Create 2 Thread objects MyThread7 t1 = new MyThread7(); MyThread7 t2 = new MyThread7(); t1.setName("cattle x"); t2.setName("Little garbage"); // Set priority 1 10 1 1 t1.setPriority(10); t2.setPriority(Thread.MIN_PRIORITY); // The start method starts t1.start(); t2.start(); } } // Define class inheritance Thread class MyThread7 extends Thread{ // Override run method @Override public void run() { // Number of prints in the run method for (int i = 0; i < 10; i++) { System.out.println(getName()+"------"+i); } } }
Thread control API (Master)
Thread sleep
static void | sleep(long millis) sleeps (pauses) the currently executing thread within a specified number of milliseconds. This operation is affected by the accuracy and accuracy of the system timer and scheduler |
---|---|
package com.cskaoyan._03api; import java.util.concurrent.TimeUnit; /** * @description: Thread sleep **/ public class SleepDemo { public static void main(String[] args) { System.out.println("1"); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("2"); // Create subclass objects ThreadSleep threadSleep = new ThreadSleep(); // start threadSleep.start(); } } class ThreadSleep extends Thread{ // run @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println(i); try { // Let the program block (wait) Thread.sleep(2000); //TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } }
Thread join
void | join() waits for the thread to terminate |
---|---|
Not used join Previous results: main start main------0 main------1 main------2 main end Thread-0------0 Thread-0------1 Thread-0------2 Thread-0------3 Thread-0------4 Thread-0------5 Thread-0------6 Thread-0------7 Thread-0------8 Thread-0------9 use join result: main start Thread-0------0 Thread-0------1 Thread-0------2 Thread-0------3 Thread-0------4 Thread-0------5 Thread-0------6 Thread-0------7 Thread-0------8 Thread-0------9 main------0 main------1 main------2 main end
Waiting for who?
Waiting is a child thread The waiting thread should be the thread calling the join method
Who is waiting?
The main thread is waiting The line of code executing the join runs on which thread, and that thread waits
package com.cskaoyan._03api; /** * @description: Thread join **/ public class JoinDemo { public static void main(String[] args) { System.out.println("main start"); // Create subclass objects ThreadJoin threadJoin = new ThreadJoin(); // start threadJoin.start(); // join() try { threadJoin.join(); } catch (InterruptedException e) { e.printStackTrace(); } for (int i = 0; i < 3; i++) { System.out.println(Thread.currentThread().getName() + "------" + i); } System.out.println("main end"); } } class ThreadJoin extends Thread{ // run @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println(getName()+"------"+i); } } }
Thread yield
static void | yield() pauses the currently executing thread object and executes other threads. |
---|---|
practice:
Create 2 Thread objects and print 10 numbers respectively
A thread print 1, B thread print 1,A thread print 2, B thread print 2
Conclusion:
It can't be done through yield
Reason: Although the current thread gives up the execution right of the CPU, it still participates in the next round of CPU competition Who grabs and who executes
package com.cskaoyan._03api; /** * @description: Thread comity **/ /* Create 2 Thread objects and print 10 numbers respectively A Thread printing 1, thread B printing 1, thread a printing 2, thread B printing 2 */ public class YieldDemo { public static void main(String[] args) { // Create 2 Thread objects ThreadYield t1 = new ThreadYield(); ThreadYield t2 = new ThreadYield(); t1.setName("A"); t2.setName("B"); // start t1.start(); t2.start(); } } class ThreadYield extends Thread{ // run @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println(getName() + "-----" + i); // Execute yield method // Pauses the currently executing thread object and executes other threads (including himself) Thread.yield(); // java uses preemptive thread scheduling } } }
daemon thread
void | setDaemon(boolean on) marks the thread as a daemon or user thread. |
---|---|
Thread classification:
- User thread
- Daemon thread
be careful
- When all running threads are daemon threads, the Java virtual machine exits.
- This method must be called before the thread is started. (start) java. Lang. illegalthreadstateexception (exception will be reported after start)
package com.cskaoyan._03api; /** * @description: Daemon thread **/ public class DaemonDemo { public static void main(String[] args) { // Create thread object ThreadDaemon t = new ThreadDaemon(); // setDaemon(boolean on) // Mark the thread as a daemon or user thread. // Set the child thread as a daemon // start t.start(); t.setDaemon(true); // Print 3 numbers in main, and sleep for 1s for each print for (int i = 0; i < 3; i++) { System.out.println(Thread.currentThread().getName() + "----" + i); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } class ThreadDaemon extends Thread{ //run @Override public void run() { for (int i = 0; i < 10; i++) { // Sleep for 1s per print System.out.println(getName() + " -------" + i); // sleep try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
Thread interrupt/stop
void | interrupt() interrupts the thread. If a thread is blocked in calling the wait(), wait(long) or wait(long, int) methods of the Object class, or the join(), join(long), join(long, int), sleep(long) or sleep(long, int) methods of the class, its interrupt state will be cleared and it will receive an InterruptedException. |
---|---|
stop() this method is inherently unsafe |
package com.cskaoyan._03api; /** * @description: Interrupt thread **/ public class InterruptDemo { public static void main(String[] args) { // Create subclass objects ThreadInterrupt t = new ThreadInterrupt(); // The start method starts t.start(); // Mainprint 3 numbers for (int i = 0; i < 3; i++) { System.out.println(Thread.currentThread().getName() + "----" + i); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } // Execute interrupt() // An exception will be generated through the exception handling mechanism //t.interrupt(); // stop unsafe t.stop(); } } class ThreadInterrupt extends Thread{ // run @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println(getName()+"-----"+i); // Sleep for 1s per print try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } // Suppose this is an operation on the database } } }
Supplementary safe termination thread
practice:
Create a sub thread. 10 sub threads are required to be printed. Each time one sub thread is printed, it will sleep for one second
The number of prints in the main thread is 3. Every time one print is dormant for 1s, it is required to terminate the thread
Use the boolean flag, which is true by default and set to false to interrupt the thread
At this time, the sub thread requires to save the interrupt information to the log file log txt
Format: 2022-01-20 16:06:00 interrupt occurred
package com.cskaoyan._03api; import java.io.FileWriter; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; /** * @description: Safe thread termination **/ /* Create a sub thread. 10 sub threads are required to be printed. Each time one sub thread is printed, it will sleep for one second main The number of prints in the thread is 3. Every time one print is dormant for 1s, it is required to terminate the thread Use the boolean flag, which defaults to true and is set to false to interrupt the thread At this time, the sub thread requires that the interrupt information be saved to the log file log txt Format: 2022-01-20 16:06:00 interrupt occurred */ public class StopSecurity { public static void main(String[] args) { // Create thread object ThreadStop t = new ThreadStop(); // start t.start(); // Print 3 numbers in main thread, and sleep for 1s for each print for (int i = 0; i < 3; i++) { System.out.println(i); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } // Interrupt the thread and change the value of flag t.flag = false; } } class ThreadStop extends Thread{ // Define member variables boolean flag = true; //run @Override public void run() { // It is required to print 10 sub threads, and sleep for one s for each print for (int i = 0; i < 10; i++) { // Judge // If true, print normally if (flag) { System.out.println(getName() + "-----" + i); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } else { // If false, the interrupt information is saved to the file // At this time, the sub thread requires that the interrupt information be saved to the log file log txt // Create a FIleWriter object FileWriter fileWriter = null; try { fileWriter = new FileWriter("log.txt"); //Format: 2022-01-20 16:06:00 interrupt occurred // Specify format SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date = sdf.format(new Date()); // write fileWriter.write(date + getName()+" An interrupt has occurred!"); // flush fileWriter.flush(); } catch (IOException e) { e.printStackTrace(); }finally { // close if (fileWriter != null) { try { fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } } } } }
Thread life cycle (focus)
Five states of threads
newly build
- new thread object
be ready
- After the start method is started, wait for the CPU to execute
implement
- Grabbed the execution power of the CPU
block
- In addition to not having the execution authority of the CPU, there are also some necessary resources, such as sleep and join
death
- The run method has finished executing
Transitions between states
Multithreading implementation mode 2: implement Runnable interface (key)
Document example
step
- Implement Runnable interface
- Override run method
- Create a subclass object that implements the Runnable interface
- Create Thread objects and Thread objects, and pass subclass objects as parameters
- The start method starts
package com.cskaoyan._04impltwo; /** * @description: Implementation mode 2 of multithreading **/ /* 1. Implement Runnable interface 2. Override run method 3. Create a subclass object that implements the Runnable interface 4. Create Thread objects and Thread objects, and pass subclass objects as parameters 5. start Method start */ public class Demo { public static void main(String[] args) { //3. Create a subclass object that implements the Runnable interface MyRunnable myRunnable = new MyRunnable(); //4. Create Thread objects and Thread objects, and pass subclass objects as parameters Thread thread = new Thread(myRunnable); //5. start method thread.start(); } } // 1. Implement Runnable interface class MyRunnable implements Runnable{ //2. Rewrite the run method @Override public void run() { System.out.println("The child thread executed!!"); } }
Why does the run method in Runnable run in a child thread?
class Thread { // Define member variables private Runnable target; init(){ //... // On the left is the member variable, and on the right is the parameter we passed this.target = target } void run(){ if(target != null){ target.run() } } }
Mode 1 VS mode 2
- Step angle: 4 steps for mode 1 and 5 steps for mode 2
- The first way is through inheritance, which has the limitation of single inheritance
- The second way is to implement the interface, which can still be inherited
- Mode 2 distinguishes the execution path from what needs to be done on the execution path (decoupling)
- Mode 2 is more convenient for data sharing
The multithreading simulation scenario is as follows:
Suppose A movie is showing in cinema A, and there are 100 movie tickets for sale. Now suppose there are 3 windows for ticket sales. Please design A program to simulate the scene of window ticket selling.
analysis:
Ticket sales at three windows are carried out at the same time without affecting each other. Multithreading 3 threads
Three windows sell the 100 movie tickets together, and three threads share the 100 tickets
Mode 1:
package com.cskaoyan._05datasecurity; /** * @description: **/ /* analysis: 3 Tickets are sold at two windows at the same time without affecting each other. Multithreading 3 threads 3 Three windows sell the 100 movie tickets together, and three threads share the 100 tickets */ public class Demo { public static void main(String[] args) { // Create 3 threads SellWindow t1 = new SellWindow(); SellWindow t2 = new SellWindow(); SellWindow t3 = new SellWindow(); t1.setName("A window"); t2.setName("B window"); t3.setName("C window"); // start t1.start(); t2.start(); t3.start(); } } class SellWindow extends Thread{ // Member variable static int tickets = 100; // run @Override public void run() { while (true) { // Simulated ticket selling // judge if (tickets > 0) { // Increase network delay try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(getName()+"Sold the second"+ (tickets--) + "ticket"); } } } }
Mode 2:
package com.cskaoyan._05datasecurity; /** * @description: **/ /* analysis: 3 Tickets are sold at two windows at the same time without affecting each other. Multithreading 3 threads 3 Three windows sell the 100 movie tickets together, and three threads share the 100 tickets */ public class Demo2 { public static void main(String[] args) { // Create subclass objects SellWindow2 sellWindow2 = new SellWindow2(); // Create 3 threads Thread t1 = new Thread(sellWindow2); Thread t2 = new Thread(sellWindow2); Thread t3 = new Thread(sellWindow2); t1.setName("A window"); t2.setName("B window"); t3.setName("C window"); // start t1.start(); t2.start(); t3.start(); } } class SellWindow2 implements Runnable{ // Member variable int tickets = 100; // run @Override public void run() { while (true) { // Simulated ticket selling // judge // Analysis: Why are there duplicate tickets // Assuming that tickets = 100, A grabs the execution right of the CPU // Suppose B grabs the execution right of the CPU if (tickets > 0) { try { // At this time, A goes to sleep // At this time, B went to sleep // At this time, c went to sleep Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+ "Sold the second"+ (tickets--) + "ticket"); // tickets -- three steps // 1. Value 2- 1 3. Reassign // Suppose A takes the value of 100 // B execution value 100 // c execution value 100 } } } }
There are two situations:
- Non existent ticket
- Duplicate ticket
Causes of multithreaded data security problems (Master)
Solve the problem of multithreaded data security (key)
synchronized
Synchronous code block
Synchronization method
Static method
lock
realization
synchronized VS lock
Deadlock (Master)
What is deadlock
Deadlock scenario
How to resolve deadlock
Mode 1
Mode II
Producer consumer model (understand)
Inter thread communication (key)
wait
notify
notifyAll
common problem
What is the difference between sleep and wait methods?