简体   繁体   中英

Reentrant Lock Problems

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?

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.

CountDownLatch latch = new CountDownLatch(1);
input = new InputPanel(config, files, latch);
JScrollPane inputScroll = new JScrollPane(input);

cySouthPanel.add("MyProgram", inputScroll);
cySouthPanel.setSelectedIndex(cySouthPanel.indexOfComponent("MyProgram"));

latch.await();

Then, in your gui code, you will need to call latch.countDown() once the button is pressed.

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.

我已经通过为程序的每个部分创建单独的线程并在它们之间交换锁来解决了这一问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM