Re-learning java basics (8): Basic knowledge of locks and java Basics
1. thread status
/*** Synchronization method ** @ author tomsnail * @ date 12:15:30 on January 1, April 18, 2015 */public synchronized void test1 () {test1 ();}
2). Fairness/unfairness
Under fair conditions, all threads that need to obtain the lock have the same chance to obtain the lock. On the contrary, some threads can obtain the lock first.
/** * Creates an instance of {@code ReentrantLock}. * This is equivalent to using {@code ReentrantLock(false)}. */ public ReentrantLock() { sync = new NonfairSync(); } /** * Creates an instance of {@code ReentrantLock} with the * given fairness policy. * * @param fair {@code true} if this lock should use a fair ordering policy */ public ReentrantLock(boolean fair) { sync = fair ? new FairSync() : new NonfairSync(); }
The ReentrantLock construction method provides a fair/unfair mechanism, while synchronized does not have a clear guarantee of fairness/non-fairness, because it is scheduled by the operating system. The specific implementation and principles of fair locks and non-fair locks will be studied later.
4. deadlock
Java is a thread-level deadlock. I borrow a deadlock from a process: it refers to the situation where multiple threads wait for resources occupied by other threads cyclically and are deadlocked for an indefinite period of time.
Conditions for deadlock:
A). mutex Conditions
A resource can only be occupied by one thread for a period of time
B). Non-preemption Conditions
Other threads cannot be preemptible before the resource is released.
C). Occupation and application conditions
This thread already occupies one resource, but applies for a new resource, but the resource to be applied for is occupied by other threads
D). Cyclic waiting Conditions
Multiple Threads wait for other threads to release resources
public class DeadLockThread { static final String a = "a"; static final String b = "b"; public static void main(String[] args) { Thread a = new Thread(new DeadLockThread1()); Thread b = new Thread(new DeadLockThread2()); a.start(); b.start(); }}class DeadLockThread1 implements Runnable{ @Override public void run() { testb(); } public void testa(){ synchronized (DeadLockThread.a) { System.out.println(DeadLockThread.a); } } public void testb(){ synchronized (DeadLockThread.b) { System.out.println(DeadLockThread.b); testa(); } } }class DeadLockThread2 implements Runnable{ @Override public void run() { testa(); } public void testa(){ synchronized (DeadLockThread.a) { System.out.println(DeadLockThread.a); testb(); } } public void testb(){ synchronized (DeadLockThread.b) { System.out.println(DeadLockThread.b); } } }
When the above four conditions are met at the same time, a deadlock will occur.
When a deadlock occurs, we can destroy the four conditions that fall down.