This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread supposed to block keyevents

 
Dajka Ferenc
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 32
IntelliJ IDE Java Scala
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It was cool. Thanks for it!
 
Darryl Burke
Bartender
Posts: 5125
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Dajka Ferenc
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok than.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic