Thread Safety, Thread Deadlock, Thread Communication Quick Start in java
One: Multithread Security
1 Introduction
Copy code
/* * Multi-threaded concurrent access to the same data resource * 3 Threads, a ticket resource, for sale */ public class ThreadDemo { public static void main(String[] args) { //Creating Runnable Interface to Implement Class Objects Tickets t = new Tickets(); //Create three Thread class objects and pass Runnable interface implementation class Thread t0 = new Thread(t); Thread t1 = new Thread(t); Thread t2 = new Thread(t); t0.start(); t1.start(); t2.start(); } }
/* * Thread hibernation causes security problems */ public class Tickets implements Runnable{ //Define the source of tickets for sale private int ticket = 100; private Object obj = new Object(); public void run(){ while(true){ //Judgment of the number of votes, greater than 0, can be sold, variable - operation if( ticket > 0){ try{ Thread.sleep(50); //Hibernation gives other threads an opportunity to execute }catch(Exception ex){} System.out.println(Thread.currentThread().getName()+" Selling "+ticket--); } } } }
Copy code
The results of the operation show that:
It can be seen that tickets are sold when the number of tickets is 0-1, which shows that there are security risks in multi-threaded operation sharing data.
Specifically, there are three threads t0,t1,t2 to operate tickets at the same time. When the program runs, three threads seize CPU resources, run if (tickets > 0) and then perform dormant operation. In this short period of 50 ms, enough CPU has done a lot of work, and continue to sell tickets. By the end of the last hibernation time, the thread does not need to judge whether tickets are greater than 0, and then proceeds down, which leads to security problems.
### 2: Solutions
2.1 Java provides synchronization mechanism, which can solve the thread security problem.
Copy code
// Synchronized code block, the lock object of synchronized code block can be any object synchronized (lock object){ Code that may cause thread security problems } // Synchronization method, the lock object in synchronization method is this public synchronized void method() Code that may cause thread security problems } // class name is the lock object in static synchronization method. public synchronized void method() Code that may cause thread security problems }
Copy code
2.2 Synchronization Method (Recommendation) or Synchronization Code Block to Solve the Thread Security Problem of the Ticket Sales Example
Copy code
public class Tickets implements Runnable {
// A total of 100 votes int tickets = 20; Object obj = new Object(); @Override public void run() { // Simulated ticket sales while (true) { method(); } } public synchronized void method() { if (tickets > 0) { // Thread Sleeping Simulation Security Problem try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "Tickets are being sold:" + tickets--); } }
}
Copy code
2.3 Principle of Synchronized Code Block
Synchronization operation puts an object lock (object monitor) on the object. Threads without the lock can not continue to execute, but can only wait.
When a thread encounters a block of synchronous code, it judges whether there is a synchronous lock or not, and then it acquires the lock and goes into synchronization to execute and releases the lock after execution. No, you can't synchronize in blocks of code
After adding synchronization, the thread enters the synchronization judgment lock, acquires the lock and releases the lock after execution, which results in the decrease of the running speed of the program.
Let's take a toilet example: Suppose there is only one toilet and only one pit (sharing data), three people A, B, C (three threads) need to go to the toilet, A takes the key first to go to the small toilet, need to open the door, this door is equivalent to the object lock, you have to open and close the door first, the small toilet for a minute (Thread.sleep). B is holding the key to open the door and go to the toilet for ten minutes. At this time C had to wait outside for B to finish.
3: Improvement of synchronized by Lock lock
There is a disadvantage of using synchronization method: if an exception occurs while sleep is dormant, the thread can not synchronize and the lock object can not be released.
Therefore, SUN provides a Lock interface after jdk5, a common method in Lock interface
void lock()
void unlock()
Copy code
public class Tickets implements Runnable {
// A total of 100 votes int tickets = 20; private Lock lock = new ReentrantLock(); @Override public void run() { // Simulated ticket sales while (true) { //Call lock method to lock lock.lock(); if (tickets > 0) { // Thread Sleeping Simulation Security Problem try { Thread.sleep(50); System.out.println(Thread.currentThread().getName()+" Selling"+tickets--); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } } }
}
Copy code
2: Thread deadlock
The disadvantage of synchronization lock: When multiple synchronizations (multiple locks) occur in thread tasks, if other synchronizations are nested in synchronization. At this time, it is easy to trigger a phenomenon: program appears infinite waiting, which we call deadlock. If this situation can be avoided, it can be avoided.
synchronzied(A lock){
synchronized(B lock){
}
}
An image analogy of deadlock: two people fight and hold each other's hair, A says you put it first, B says you put it first, neither of them will let it go first, which causes deadlock.
Here's an example of deadlock generation
Copy code
public class lockA {
//Guarantee the Uniqueness of Objects private lockA(){ } public final static lockA locka = new lockA();
}
public class LockB {
//Guarantee the Uniqueness of Objects private LockB() { } public static final LockB lockb = new LockB();
}
public class DeadLock implements Runnable {
private int i = 0; @Override public void run() { while (true) { if (i % 2 == 0) { // First enter A synchronization, then enter B synchronization synchronized (lockA.locka) { System.out.println("if---locka"); synchronized(LockB.lockb){ System.out.println("if---lockb"); } } } else { //Advanced Entry B Synchronization and Entry A Synchronization synchronized (LockB.lockb) { System.out.println("else---lockb"); synchronized(lockA.locka){ System.out.println("else---locka"); } } } i++; } }
}
public class DeadLockDemo {
public static void main(String[] args) { DeadLock deadLock = new DeadLock(); Thread t0 = new Thread(deadLock); Thread t1 = new Thread(deadLock); t0.start();t1.start(); }
}
Copy code
Threaded communication
Communication between threads: Multiple threads are dealing with the same resource, but the actions (tasks of threads) are different. Through certain means, each thread can make effective use of resources. And that means waiting for the wake-up mechanism.
Let's make an analogy: just like receiving express delivery at ordinary times, express delivery is packaged by the seller first, contacts the recipient to receive and receive the goods, and the express delivery is transferred to you all the way through various locations. Think of this series of processes as threads. All threads work together to process your package, so as to make effective use of resources.
Waiting for wake-up mechanisms involves methods:
wait (): wait, release the execution qualifications and execution rights of the executing thread, and store them in the thread pool.
notify (): Wake up, wake up a thread in the thread pool that is wait ing (), wake up one at a time, and it's arbitrary.
notifyAll (): Wake up all: You can wake up all wait() threads in the thread pool.
In fact, the so-called wake-up means that the thread in the thread pool is qualified for execution. It must be noted that these methods are effective in synchronization. At the same time, these methods must indicate the locks they belong to when they are used, so as to determine which thread on which locks these methods operate.
Looking closely at the Java API, we find that these methods are not defined in Thread, nor in Runnable interface, but in Object class. Why are these methods for manipulating threads defined in Object class?
Because when these methods are used, they must indicate the locks they belong to, and the locks can be arbitrary objects. Methods that can be called by any object must be defined in the Object class.
The Java implementation code is as follows:
Copy code
Implementation of A Thread Waiting and Waking Case
/* * Define resource classes with two member variables * name,sex * There are also two threads that operate on variables in the resource * 1 Assignment of name and age * 2 Output printing of variables for name and age */ public class Resource { public String name; public String sex; public boolean flag = false; } /* * Input threads assign values to member variables in Resource object resources * One assignment Zhang San, male * Next assignment lisi,nv */ public class Input implements Runnable { private Resource r ; public Input(Resource r){ this.r = r; } public void run() { int i = 0 ; while(true){ synchronized(r){ //The tag is true, wait if(r.flag){ try{r.wait();}catch(Exception ex){} } if(i%2==0){ r.name = "Zhang San"; r.sex = "male"; }else{ r.name = "lisi"; r.sex = "nv"; } //Wake up the other thread and change the marker to true r.flag = true; r.notify(); } i++; } } } /* * Output threads, member variables in Resource object resources, output values */ public class Output implements Runnable { private Resource r ; public Output(Resource r){ this.r = r; } public void run() { while(true){ synchronized(r){ //Judgment flag, false, wait if(!r.flag){ try{r.wait();}catch(Exception ex){} } System.out.println(r.name+".."+r.sex); //Change the tag to false to wake up the other thread r.flag = false; r.notify(); } } } } /* * Open input and output threads to assign and print values */ public class ThreadDemo{ public static void main(String[] args) { Resource r = new Resource(); Input in = new Input(r); Output out = new Output(r); Thread tin = new Thread(in); Thread tout = new Thread(out); tin.start(); tout.start(); } }
Copy code
The output results are as follows: (Complete the collaborative work, output after assignment, assignment after output)
Original address https://www.cnblogs.com/zengcongcong/p/11318686.html