gpt4 book ai didi

java - 基于id的线程同步

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:08:49 25 4
gpt4 key购买 nike

我需要一种方法来只允许一个线程修改与服务票证相关的数据。可能有多个线程同时尝试修改工单数据。

下面是我的方法的简化版本。有一个更好的方法吗?也许使用 java.util.concurrent 包?

public class SomeClass1
{
static final HashMap<Integer, Object> ticketLockMap = new HashMap<Integer, Object>();


public void process(int ticketNumber)
{
synchronized (getTicketLock(ticketNumber))
{
// only one thread may modify ticket data here

// ... ticket modifications here...
}
}


protected static Object getTicketLock(int ticketNumber)
{
Object ticketLock;

// allow only one thread to use map
synchronized (ticketLockMap)
{
ticketLock = ticketLockMap.get(ticketNumber);

if (ticketLock == null)
{
// first time ticket is locked
ticketLock = new Object();
ticketLockMap.put(ticketNumber, ticketLock);
}
}

return ticketLock;
}
}

此外,如果我不希望 HashMap 充满未使用的锁,我将需要一种更复杂的方法,如下所示:

public class SomeClass2
{
static final HashMap<Integer, Lock> ticketLockMap = new HashMap<Integer, Lock>();


public void process(int ticketNumber)
{
synchronized (getTicketLock(ticketNumber))
{
// only one thread may modify ticket data here

// ... ticket modifications here...

// after all modifications, release lock
releaseTicketLock(ticketNumber);
}
}


protected static Lock getTicketLock(int ticketNumber)
{
Lock ticketLock;

// allow only one thread to use map
synchronized (ticketLockMap)
{
ticketLock = ticketLockMap.get(ticketNumber);

if (ticketLock == null)
{
// first time ticket is locked
ticketLock = new Lock();
ticketLockMap.put(ticketNumber, ticketLock);
}
}

return ticketLock;
}


protected static void releaseTicketLock(int ticketNumber)
{
// allow only one thread to use map
synchronized (ticketLockMap)
{
Lock ticketLock = ticketLockMap.get(ticketNumber);

if (ticketLock != null && --ticketLock.inUseCount == 0)
{
// lock no longer in use
ticketLockMap.remove(ticketLock);
}
}
}
}


class Lock
{
// constructor/getters/setters omitted for brevity
int inUseCount = 1;
}

最佳答案

您可能正在寻找 Lock interface .第二种情况可以通过 ReentrantLock 解决。 , 它计算它被锁定的次数。

锁有一个 .lock()等待获取锁的方法和一个 .unlock应该像这样调用的方法

 Lock l = ...;
l.lock();
try {
// access the resource protected by this lock
} finally {
l.unlock();
}

然后可以将其与 HashMap<Integer, Lock> 结合使用.你可以省略 synchronized调用并减少代码行数。

关于java - 基于id的线程同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17069569/

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