簡體   English   中英

等待后如何解鎖

[英]How is unlock happening after await

我寫了一個小程序來交替打印奇偶數,但有一個問題:

由於線程應該在await調用時await那么可重入鎖是如何解鎖的?

public class Worker implements Runnable
{
    private ReentrantLock rLock = null;
    private Condition condition = null;
    private String name;
    volatile static boolean isEvenTurn = true;
    
    public Worker(String name, ReentrantLock rLock, Condition condition)
    {
        this.name = name;
        this.rLock = rLock;
        this.condition = condition;
    }
    
    @Override
    public void run() 
    {
        try
        {
            if(name.equals("ODD"))
                printOdd();
            else
                printEven();
        }
        catch(Exception e) { e.printStackTrace();}
        
    }
    
    private void printOdd() throws Exception
    {
        while(isEvenTurn);
        for(int i=1;i<10;i+=2)
        {
            try
            {
                rLock.lock();
                System.out.println(i);
            }
            catch(Exception e) {e.printStackTrace();}
            finally
            {
                condition.signal();
                condition.await();
                rLock.unlock();
            }
        }
    }
    
    private void printEven() throws Exception
    {
        for(int i=0;i<10;i+=2)
        {
            try
            {
                rLock.lock();
                System.out.println(i);
                isEvenTurn = false;
            }
            catch(Exception e) {e.printStackTrace();}
            finally
            {
                condition.signal();
                condition.await();
                rLock.unlock();
            }
        }
    }
    
    public static void main(String[] args) 
    {
        ReentrantLock rLock = new ReentrantLock();
        ExecutorService service = Executors.newFixedThreadPool(2);
        
        Condition c = rLock.newCondition();
        Worker oddPrinter = new Worker("ODD",rLock,c);
        Worker evenPrinter = new Worker("EVEN",rLock,c);
        
        service.execute(evenPrinter);
        service.execute(oddPrinter);
        
        service.shutdown();
    }
}

在 printEven() 方法中添加這一行:在 finally 塊中:

       finally
        {
            condition.signal();
            if(i < 10)condition.await(); 
            rLock.unlock();
        }

通過添加此條件,當您的 i = 10 時,您的線程將不再等待。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM