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.
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: