可重入锁问题
我正在编写一个程序,该程序创建一个用户输入窗格,并且需要等待用户单击“查询”才能执行任何计算。目前,我正在使用 ReentrantLock 来执行此操作。
input = new InputPanel(config, files, runLock);
JScrollPane inputScroll = new JScrollPane(input);
cySouthPanel.add("MyProgram", inputScroll);
cySouthPanel.setSelectedIndex(cySouthPanel.indexOfComponent("MyProgram"));
runLock.lock();
try {
// do stuff
}
finally {
runLock.unlock();
}
我目前在 InputPanel 的构造函数中获取锁,并在用户单击“查询”按钮时释放它,但我的程序在遇到上面的 runLock.lock()
时不会停止。有什么想法吗?
编辑:我的问题源于这样一个事实:InputPanel 与我上面描述的函数在同一线程中运行。在这种情况下,lock()
不会阻塞。
我需要一种方法来等待程序等待InputPanel。创建我自己的线程是一个可行的选择吗?
I'm writing a program that creates a user input pane and needs to wait for the user to click "query" before it performs any calculations. Currently, I'm using a ReentrantLock to do this.
input = new InputPanel(config, files, runLock);
JScrollPane inputScroll = new JScrollPane(input);
cySouthPanel.add("MyProgram", inputScroll);
cySouthPanel.setSelectedIndex(cySouthPanel.indexOfComponent("MyProgram"));
runLock.lock();
try {
// do stuff
}
finally {
runLock.unlock();
}
I currently acquire the lock in the constructor of InputPanel and release it when the user clicks the 'query' button, but my program does not stop when it encounters runLock.lock()
above. Any ideas as to why?
EDIT: My problem stems from the fact that the InputPanel runs in the same thread as the function that I have described above. In this case lock()
does not block.
I need a way to wait for the program to wait for the InputPanel. Would creating my own threads be a viable alternative?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编辑
听起来您想要做的是使用
CountDownLatch
。您将创建值为 1 的锁存器 (new CountDownLatch(1)
)。然后等待。然后,在您的 GUI 代码中,按下按钮后您需要调用
latch.countDown()
。Edit
What it sounds like you will want to do is use a
CountDownLatch
. You will create the latch with a value of 1 (new CountDownLatch(1)
). And then await.Then, in your gui code, you will need to call
latch.countDown()
once the button is pressed.我想知道这是否取决于时间。您可能会找到 CountDownLatch ( http://download .oracle.com/javase/6/docs/api/java/util/concurrent/CountDownLatch.html )更适合您想做的事情。
I wonder if it is down to timing. You might find a CountDownLatch ( http://download.oracle.com/javase/6/docs/api/java/util/concurrent/CountDownLatch.html ) a better fit for what you want to do.
我通过为程序的每个部分创建单独的线程并在它们之间交换锁来解决这个问题。
I have solved this by creating separate threads for each part of the program and exchanging the lock between them.