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. Cur开发者_JAVA百科rently, 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.
I have solved this by creating separate threads for each part of the program and exchanging the lock between them.
精彩评论