Synchronization mechanism
1, Synchronization block
When multiple threads operate on the same data, data errors and data insecurity are caused.
Solution: when multiple threads operate on the same data, only one thread can operate on the data at a time
The synchronization block syntax used in Java is as follows:
synchronized(obj) {/ / where obj represents any reference type object
......
}
Task class:
public class MyR2 implements Runnable{ public static Object obj = new Object(); @Override public void run() { synchronized (obj){ System.out.println(Thread.currentThread().getName()+"----"+ ++Demo1.num); } } }
Test class:
public static int num = 0; public static void main(String[] args) { Thread t1 = new Thread(new MyR2()); Thread t2 = new Thread(new MyR2()); Thread t3 = new Thread(new MyR2()); Thread t4 = new Thread(new MyR2()); Thread t5 = new Thread(new MyR2()); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); }
Recommendation:
Synchronizes the code in the code block to place the operation variable.
Supplementary knowledge:
Control the current thread to release the lock object:
Lock object. Wait (millisecond value); =======> lock object. wait(1);
2, Synchronization method
public static void main(String[] args) { //Requirements: different threads and different methods Thread t1 = new Thread(new Runnable() { @Override public void run() { fun1(); } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { fun1(); } }); t1.start(); t2.start(); } //Synchronization method: only one thread can execute at a time //Synchronization method: static: class object // Non static: this object public static synchronized void fun1(){ System.out.println(Thread.currentThread().getName()+"fun1 Here we go"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"fun1 Implemented"); System.out.println(Thread.currentThread().getName()+"fun1 It's over"); }
Let only one thread execute code at a time.
Synchronize code block: synchronize only a part of code
Synchronization method: the entire method is synchronized
Synchronous code blocks are recommended.
Synchronize one thread at a time
3, Data sharing among multiple threads
Risk: multiple threads operate on the same data at the same time, which may cause data duplication.
Solve:
- Multithreading only reads shared objects / data (no writes)
- Joint synchronization (synchronization code block / synchronization method) when multithreading writes shared data
Example:
Demand:
1. Use multi-threaded method to complete the multi window co selling of 10 tickets.
Realize alternative ticket sales
In alternation, the order of window appearance can be disordered
Analysis:
- Votes, saved in variable
- Ticket selling task
- Window 1, window 2, window 3 ---- thread 1, thread 2, thread 3
Code implementation:
- Task class
-
public class SellTicket implements Runnable{ //10 tickets in total public static int num = 10; public static Object obj = new Object(); @Override public void run() { //Circulation of tickets synchronized (obj){ while (num>=1){ System.out.println(Thread.currentThread().getName()+"Sell a ticket:"+ --num); //Sell a ticket and release the lock object try { obj.wait(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
2. test class
public static void main(String[] args) { //A window is a thread Thread t1 = new Thread(new SellTicket(), "Window 1"); Thread t2 = new Thread(new SellTicket(), "Window 2"); Thread t3 = new Thread(new SellTicket(), "Window 3"); t1.start(); t2.start(); t3.start(); }
Multithreaded summary:
1. Process: a running program, which is an independent unit of resource allocation and call of the system
2, Thread: it is a single sequential control flow in the process and an execution path (execution line)
3,
Multithreading: a process has multiple execution paths
The execution efficiency is very high, and the execution speed remains the same.
Defect: results are random
Single thread: a process has only one execution path
The result is fixed.
Defect: inefficient execution
4,
The significance of multithreading: not to improve the speed of execution, but to improve the utilization rate of programs
5. Thread Concurrency: refers to running multiple threads at the same time in a certain time
6. JVM virtual machine start is multithreaded: because the JVM starts at least the garbage collection thread and the main thread
7. The thread cannot be started multiple times, otherwise an error is reported.
8. start() starts a new thread and executes the run method of the task class.
run() executes the task class run method in the current thread.
9. CPU scheduling method of Java thread:
Preemptive scheduling: give priority to threads with high priority to use CPU. If the priority is the same, select one randomly.
Higher priority threads use more CPU
sleep()
Implement Runnable
Inherit Thread class
Synchronization mechanism: turn multithreading into a single thread
Synchronization code block:
synchronized(obj) {/ / where obj represents any reference type object
......
}
obj: lock object. Which thread gets the lock object has the right to execute the mutex code
synchronized code block: mutually exclusive area.
All threads that can enter this area have lock objects
Threads without lock objects are excluded from the mutex area
Synchronization method:
synchronized
static method: lock object Class object of current Class
Non static method: lock object this
A synchronization code block keeps a lock object
synchronized(obj){
}
synchronized(new Object()){
//Each thread will get a lock object, and more than one thread will run in the mutex area
//Mutually exclusive area is meaningless
}
Lock object. Wait (millisecond value); let the current thread wait X milliseconds. Release lock object now
After the current thread waits for X milliseconds, it will scramble for the lock object again
Please give yourself a compliment!
Make a little progress every day`~~~~~