File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes Thread supposed to block keyevents Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Thread supposed to block keyevents" Watch "Thread supposed to block keyevents" New topic

Thread supposed to block keyevents

Dajka Ferenc

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

Joined: Mar 09, 2012
Posts: 6
It was cool. Thanks for it!
Darryl Burke

Joined: May 03, 2008
Posts: 5115

Dajka, please BeForthrightWhenCrossPostingToOtherSites

edit And

Any more?

luck, db
There are no new questions, but there may be new answers.
Dajka Ferenc

Joined: Mar 09, 2012
Posts: 6
ok than.
I agree. Here's the link:
subject: Thread supposed to block keyevents
It's not a secret anymore!