1. 程式人生 > >Java簡單鎖機制,synchronized死鎖並解決

Java簡單鎖機制,synchronized死鎖並解決

下面例子有一定概率deadLock

import com.sun.org.apache.regexp.internal.RE;

/**
 * Created by butter on 16/11/15.
 */

class Resource{
    private String name;
    private int resource;

    public Resource(String name, int resource) {
        this.name = name;
        this.resource = resource;
    }
    synchronized
void doSome(){ System.out.println("doing some thing"); resource++; } synchronized void cooperate(Resource resource){ System.out.println("cooperating"); resource.doSome(); } } /** * * 兩個Resource物件 r1, r2 * 兩個執行緒t1, t2 * t1呼叫cooperate(r2)時獲取r1的鎖,如果此時此刻t2正在呼叫cooperate(r1)將獲取r2的鎖 * 這時,t1.cooperate(r2)執行r2.doSome(),將申請獲取r2的鎖,r2鎖被t2獲取,所以等待 * 並且,t2.cooperate(r1)執行r1.doSome(),將申請獲取r1的鎖,r1的鎖被t1獲取,繼續等待, * * 結果就是t1 等 t2 的鎖 t2 等 t1 的鎖,互相等待對方的鎖,造成死鎖 */
public class Demo_deadLock { public static void main(String[] args) { Resource r1 = new Resource("1", 1); Resource r2 = new Resource("2", 2); // 迴圈次數多一些,為了得到上述情況 Thread thread1 = new Thread(()->{ for (int i = 0; i < 100; i++) { r1.doSome(); r1.cooperate(r2); } }); System.out.println("t1 over"
); Thread thread2 = new Thread(()->{ for (int i = 0; i < 100; i++) { r2.doSome(); r2.cooperate(r1); } }); thread1.start(); thread2.start(); System.out.println("t2 over"); } }

解決方案:

import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by butter on 16-11-17.
 */
/**
 * 
 * 每次執行緒嘗試獲取lock,獲取不到,釋放已有lock,解決deadlock
 * 
 */


class Resource1{

    private String name;
    private int resource;
    private ReentrantLock lock = new ReentrantLock(); //Lock介面

    public Resource1(String name, int resource) {
        this.name = name;
        this.resource = resource;
    }
    void doSome(){

        System.out.println(Thread.currentThread().getName() + " doing some thing: " + name+ " " + resource);
        resource++;
    }
    void cooperate(Resource1 resource){
        while(true) {
            try {
                if (lockMeAnd(resource)) {
                    System.out.println(Thread.currentThread().getName() + "  r1 & r2 has been Locked");
                    System.out.println(Thread.currentThread().getName() + " cooperating");
                    resource.doSome();
                    break;
                } else {
                    System.out.println( Thread.currentThread().getName() +"       can't lock r1&r2");
                }
            }finally {
                unLockMeAnd(resource);
                System.out.println(Thread.currentThread().getName() + " r1 & r2 has been unLocked");
            }

        }
    }

    private boolean lockMeAnd(Resource1 res){
        /*嘗試獲取鎖, 獲取不到->不阻塞*/
        return this.lock.tryLock() && res.lock.tryLock();
    }
    private void unLockMeAnd(Resource1 res){
        if(this.lock.isHeldByCurrentThread()){
            this.lock.unlock();
        }
        if(res.lock.isHeldByCurrentThread()){
            res.lock.unlock();
        }
    }
}


public class Demo_noDeadLock {
    public static void main(String[] args) {
        Resource1 r1 = new Resource1("a", 1);
        Resource1 r2 = new Resource1("b", 2);

        Thread t1 = new Thread(()->{
            for (int i = 0; i < 10; i++) {
                r1.cooperate(r2);
            }
        });
        Thread t2 = new Thread(()->{
            for (int i = 0; i < 10; i++) {
                r2.cooperate(r1);
            }
        });
        t1.start();
        t2.start();
    }
}