A thread holds a resource, it needs to obtain the release of a resource Resources b.
B two threads hold resources, need to acquire a resource is not released b resources.
Cause a deadlock.
Below is an example:
The two women make-up, you need a mirror and lipstick, two people acquire a mirror, let's use lipstick, lipstick acquire another, then let the mirror
/** * @Author TEDU * Deadlock occurs mostly lock lock sets. */ public class DeadLock { public static void main(String[] args) { MakeUp m1 = new MakeUp("小红",1); MakeUp m2 = new MakeUp("小丽",2); m1.start(); m2.start(); } } //mirror class Mirror{ } // lipstick class Lipstick{ } //make up class MakeUp extends Thread{ // Here is a static modification, to ensure that they get is with a mirror and lipstick private static Mirror mirror = new Mirror(); private static Lipstick lipstick = new Lipstick(); private String name; private int choice; public MakeUp(String name,int choice) { this.name = name; this.choice = choice; } @Override public void run() { // TODO Auto-generated method stub super.run(); makeUp(choice); } public void makeUp(int choice) { if(choice == 1) { synchronized (mirror){ // acquire the mirror System.out.println (name + "took the mirror"); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace (); } synchronized (lipstick) {// write in the lock of locks: Take lipstick // retook the mirror System.out.println (name + "took the lipstick"); } } }else { synchronized (lipstick){ // acquire lipstick System.out.println (name + "took the lipstick"); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace (); } synchronized (mirror) {// write lock in the lock: Take Mirror // retook the mirror System.out.println (name + "took the mirror"); } } } } }
This program will result in a deadlock.
This example Solution: put down the existing resources (unlocked), and then get another resource.
That is, unlocking the locking sleeve, will go down in sync blocks in the sync block out side by side can be.
if(choice == 1) { synchronized (mirror){ // acquire the mirror System.out.println (name + "took the mirror"); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace (); } } synchronized (lipstick) {// lock alone write: Take lipstick // retook the mirror System.out.println (name + "took the lipstick"); } }