one, the thread lockThread safety issues
In fact, thread safety problems are caused by global variables and static variables . In general, this global variable is thread-safe if there are only read operations on the global variable and static variables in each thread, and if multiple threads are concurrently performing write operations, thread synchronization is generally required, otherwise it may affect thread safety.
Because of the nature of thread hibernation, from where to go to sleep from where to continue execution (a thread of things have not been done before the other threads squeeze down), back to continue to dry will cause the operation of global variables or static variables problems.
In order to solve this problem, we need to have the thread executed (cannot be squeezed by other threads), here are a few workarounds.
1. Synchronizing code blocks
Ensure that the code block executes and then switches the thread.
Formula:
Synchronized (arbitrary object) {
Shared data to be manipulated by the thread
}
Call class
public class Threaddemo {public static void Main (string[] args) { Ticket tk = new Ticket (); Thread t01 = new Thread (TK); Thread t02 = new Thread (TK); Thread t03 = new Thread (TK); T01.start (); T02.start (); T03.start (); }}
Synchronizing code blocks
public class Ticket implements Runnable { //definition for sale votes private int Ticket = +; public void Run () {while (true) { //because it can be filled with arbitrary objects, you can use this (representing the currently instantiated ticket object TK) synchronized (this) { //The number of votes judged, greater than 0, can be sold, variable--operation if (Ticket > 0) { System.out.println (Thread.CurrentThread (). GetName () + "Sale" "+ ticket--);}}}}
The lock object in a synchronous code block can be any object, but when multiple threads are used, the same lock object is required to ensure thread safety.
2. Synchronization method
You can also extract a block of code that needs to be synchronized by extracting a method that uses the synchronized field decoration.
Public synchronized Void method () {
Code that could cause thread safety issues
}
Synchronization method
public class Ticket implements Runnable { //definition for sale votes private int Ticket = +; public void Run () { while (true) { func ()} } Private synchronized void Func () { //pair of votes judged, greater than 0, can be sold, variable--operation if (Ticket > 0) { System.out.println ( Thread.CurrentThread (). GetName () + "sale" + ticket--);} }
The lock object in the synchronization method is this, and the synchronous lock is the class name if it is a static synchronization method. Class
3. Lock Interface
public class Ticket implements runnable{ //definition for sale votes private int Ticket = +; In the member location of the class, create the implementation class object of the lock interface private lock lock = new Reentrantlock (); public void Run () {while (true) { //Call Lock interface method Lock acquires lock Lock.lock (); The number of votes judged, greater than 0, can be sold, variable--operation if (Ticket > 0) { try{ //execute code System.out.println that may cause thread safety issues ( Thread.CurrentThread (). GetName () + "Sale" +ticket--); catch (Exception ex) { }finally{ //release lock, call Lock interface method unlock lock.unlock (); } }}}
Two, deadlock
The disadvantage of using synchronous locks: When multiple synchronizations ( multiple locks ) occur in a thread task, other synchronizations are nested in the synchronization. At this point it is easy to trigger a phenomenon: The program has infinite wait, this phenomenon we call a deadlock. This situation can be avoided by avoiding it.
three, waiting for the wake-up mechanismcommunication between Threads:
Multiple threads are working on the same resource, but the actions that are processed (the task of the thread) are not the same. Through a certain means to enable each thread to effectively utilize resources. And that means-- wait for the awakening mechanism.
wait for wake-up mechanism
The methods involved in waiting for the wake-up mechanism:
In fact, the so-called wake-up means that threads in the thread pool are eligible for execution. It is important to note that these methods are only valid in synchronization. At the same time, these methods must be used to indicate the owning lock, so as to be able to clarify which of these methods operation is exactly which locked thread.
After a closer look at Javaapi , it is found that these methods are not defined in Thread , nor defined in the Runnable interface, but are defined in the Object class. Why are the methods of these operations threads defined in the Object class?
Because these methods are used, they must be marked with the lock they belong to, and the lock can be any object . Methods that can be called by arbitrary objects must be defined in the object class.
1 PackageCn.x5456.demo;2 3 Public classThreaddemo {4 Public Static voidMain (string[] args) {5Resource r =NewResource ();6 7 //Sharing Data8Input in =NewInput (r);9Output out =NewOutput (r);Ten OneThread tin =NewThread (in); AThread tout =NewThread (out); - - Tin.start (); the Tout.start (); - } -}
Threaddemo
1 PackageCn.x5456.demo;2 3 Public classInputImplementsrunnable{4 PrivateResource R;5 inti = 0;6 7 PublicInput (Resource r) {8 This. r=R;9 }Ten One A Public voidrun () { - while(true){ - synchronized(r) {//to use the same object, look at the input and output two synchronization methods (otherwise they go separately) the if(r.flag) { - Try { -R.wait ();//use the same object to wait + start -}Catch(interruptedexception e) { + e.printstacktrace (); - } + } A if(i%2==0){ atR.name = "Zhang San"; -R.sex = "Male"; -}Else{ -R.name = "Lisi"; -R.sex = "NV"; - } ini++; -R.flag =true; toR.notify ();//Wake up the other side + } - } the } *}
Input
1 PackageCn.x5456.demo;2 3 Public classOutputImplementsrunnable{4 PrivateResource R;5 6 PublicOutput (Resource r) {7 This. R =R;8 }9 Ten One @Override A Public voidrun () { - while(true){ - synchronized(r) { the if(!R.flag) { - Try { - r.wait (); -}Catch(interruptedexception e) { + e.printstacktrace (); - } + } ASystem.out.println (r.name+ "..." +r.sex); at //flag changed to False to wake the other thread -R.flag =false; - r.notify (); - } - } - } in}
Output
1 Package Cn.x5456.demo; 2 3 Public class Resource {4 String name; 5 String sex; 6 Boolean false ; 7 }
Resource
java--thread Lock, deadlock, wait for wake-up mechanism