gpt4 book ai didi

java - 为什么 ReentrantLock 在 SpringXD 中不起作用

转载 作者:行者123 更新时间:2023-12-01 21:26:07 24 4
gpt4 key购买 nike

我试图在 SpringXD 的工作中添加 ReentrantLock,但有时似乎跨线程会出现中断。

例如,我有这些代码:

public class LoadGenerator extends MessageProducerSupport {

private final AtomicBoolean running = new AtomicBoolean(false);
private ExecutorService executorService;

Logger logger = LoggerFactory.getLogger(LoadGenerator.class);

public LoadGenerator(){}

@Override
protected void doStart() {
executorService = Executors.newFixedThreadPool(2);
if (running.compareAndSet(false, true)) {
for (int x = 0; x < 10; x++) {
executorService.submit(new Producer(Integer.toString(x)));
}
}
}

@Override
protected void doStop() {
if (running.compareAndSet(true, false)) {
executorService.shutdown();
}
}

protected class Producer implements Runnable {
String prefix;
Lock lock = new ReentrantLock();

public Producer(String prefix) {
this.prefix = prefix;
}

private void send() {
lock.lock();
try{
for(int i = 0; i < 10; i++){
System.out.println(Thread.currentThread().getName() + " " + i);
}
}finally{
lock.unlock();
}
}

public void run() {
send();
}
}
}

我期望的是一个类似的列表

pool-604-thread-1 0
pool-604-thread-1 1
pool-604-thread-1 2
pool-604-thread-1 3
pool-604-thread-1 4
pool-604-thread-1 5
pool-604-thread-1 6
pool-604-thread-1 7
pool-604-thread-1 8
pool-604-thread-1 9
pool-604-thread-2 0
pool-604-thread-2 1
pool-604-thread-2 2
pool-604-thread-2 3
pool-604-thread-2 4
pool-604-thread-2 5
pool-604-thread-2 6
pool-604-thread-2 7
pool-604-thread-2 8
pool-604-thread-2 9
...

每个线程中的顺序和顺序不应该被中断,但事实是有时会出现中断,例如:

pool-604-thread-1 0
pool-604-thread-2 0
pool-604-thread-2 1
pool-604-thread-2 2
pool-604-thread-1 1
pool-604-thread-1 2
pool-604-thread-1 3

出了什么问题?该锁在 Eclipse 上的本地主机中运行良好,经过测试。

是因为SpringXD是分布式系统吗?但我只有一个 xdcontaier 连接到我的 xdadmin。

谢谢。

最佳答案

您应该传递您的ReentrantLock,而不是在每个新的Runnable中创建它,生产者应该共享一个ReentrantLock ,例如:

@Override
protected void doStart() {
executorService = Executors.newFixedThreadPool(2);
Lock lock = new ReentrantLock(); // create a share lock to lock in multi threads
if (running.compareAndSet(false, true)) {
for (int x = 0; x < 10; x++) {
executorService.submit(new Producer(Integer.toString(x), lock)); //pass this lock to every producer
}
}
}
protected class Producer implements Runnable {
String prefix;
final Lock lock;

public Producer(String prefix, Lock lock) {
this.prefix = prefix;
this.lock = lock;
}

private void send() {
lock.lock();
try{
for(int i = 0; i < 10; i++){
System.out.println(Thread.currentThread().getName() + " " + i);
}
}finally{
lock.unlock();
}
}

public void run() {
send();
}
}

关于java - 为什么 ReentrantLock 在 SpringXD 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38119658/

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