在java中最简单的Lock实现

时间:2010-09-15 01:45:02

标签: java concurrency locking

  

可能重复:
  Peterson algorithm in Java?

我试图在petersen方法的行中实现Java(锁定接口)中的锁。什么是最简单的非重入实现以保证互斥。

flag[0]   = 0;
flag[1]   = 0;
turn;

P0: flag[0] = 1;                            P1: flag[1] = 1;
    turn = 1;                                   turn = 0;
    while (flag[1] == 1 && turn == 1)           while (flag[0] == 1 && turn == 0)
    {                                           {
           // busy wait                                  // busy wait
    }                                           }                                 
    // critical section                         // critical section 
       ...                                        ...
    // end of critical section                  // end of critical section
    flag[0] = 0;                                flag[1] = 0;

我正在使用上面的算法(来自wiki)。尽管使用volatile标志和转向变量,但它似乎没有工作,因为我获得了许多数据竞赛。有什么需要照顾的?

这里是代码:

public class TestLock implements Lock {

    private final long thread1ID;
    private final long thread2ID;
    private volatile AtomicIntegerArray flagArr = new AtomicIntegerArray(50);
    private volatile long turn = 0;
    private volatile long currentThreadID = 0;

    public TestLock(Thread thread1, Thread thread2) {       
        thread1ID = t0.getId();
        thread2ID = t1.getId();         
        flagArr.set((int)thread1ID, 0);
        flagArr.set((int)thread2ID, 0);     
    }
    public void lock() {        
        currentThreadID = Thread.currentThread().getId();
        flagArr.set((int)Thread.currentThread().getId(), 1);            
        turn = next();          
        while(turn == next() && flagArr.get((int)next()) == 1)
        {
            System.out.println(Thread.currentThread().getId()+" waiting");              
        }
        //critical section
        System.out.println(Thread.currentThread().getId()+" executing");
        }

    private long next() {
        return Thread.currentThread().getId() == thread1ID ? thread2ID : thread1ID;     
    }

    public void unlock() {      
        flagArr.set((int)Thread.currentThread().getId(), 0);    
    }
}

1 个答案:

答案 0 :(得分:0)

嗯,根据this SO question接受的答案中的评论,一个问题是您不能使用boolean []并期望单元格具有volatile语义。

如果您发布了代码,我们可能会提供更多建议。