| Author |
Thread supposed to block keyevents
|
Dajka Ferenc
Greenhorn
Joined: Mar 09, 2012
Posts: 6
|
|
Hi There!
I wrote 2 class, the first is a canvas wich can listen to keyevents, the second is a thread wich sets a boolean variable to true, than 2 secs later to false. While the variable is true, one shouldnt supposed to change anything with a keypress, but one can. How can this be possible? Thanks.
The listeners code.
the threads code:
|
 |
Alexander Kober
Ranch Hand
Joined: Aug 05, 2011
Posts: 32
|
|
There are at least two things wrong with the implementation:
1) It seems you start a thread and immediately expect it to be running. This is not the case. Thread#start schedules a thread for execution, but that may happen at any time. Usually, thread startup will happen very fast, but not immediately.
2) Though this is may be unintuitive, never use a plain boolean for synchronization between threads, at the very least make it volatile or use an AtomicBoolean.
That being said, if I understand your code correctly, you simply want to block key input for 2 seconds, correct? Why create a thread in the first place then? When your keyPressed method is executed, take the current system time (System.currentTimeMillis()) and assign it to a variable. Simply add a check at the beginning of the method to see when the last keyPress was processed:
|
 |
Dajka Ferenc
Greenhorn
Joined: Mar 09, 2012
Posts: 6
|
|
|
It was cool. Thanks for it!
|
 |
Darryl Burke
Bartender
Joined: May 03, 2008
Posts: 4166
|
|
Dajka, please BeForthrightWhenCrossPostingToOtherSites
http://www.java-forums.org/threads-synchronization/56540-thread-supposed-block-keyevents.html
edit And http://www.programmingforums.org/thread40728.html
Any more?
|
luck, db
There are no new questions, but there may be new answers.
|
 |
Dajka Ferenc
Greenhorn
Joined: Mar 09, 2012
Posts: 6
|
|
|
ok than.
|
 |
 |
|
|
subject: Thread supposed to block keyevents
|
|
|