gpt4 book ai didi

java - 等待后解锁如何发生

转载 作者:行者123 更新时间:2023-12-03 13:23:20 24 4
gpt4 key购买 nike

我编写了一个小程序来交替打印奇偶数,但是有一个问题:
由于线程应等待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,您的线程将不再等待。

关于java - 等待后解锁如何发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63716866/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com