java - Should input listeners be synchronized? -
my sample code posted below shows 2 classes. 1 implements keylistener , other implements runnable , running in infinite loop sleeping every 20 ms. when key pressed keychar, in form of int, used index setting index of boolean array true or false, representing key pressed or not. @ same time process loop searching key array true or false values , setting true ones false printing out char. question whether or not need use synchronization using lock accessing chararray because used in 2 threads: process thread , key listener thread.
sample code:
import java.awt.component; import java.awt.event.keyevent; import java.awt.event.keylistener; public class input implements keylistener { public boolean[] chararray; public input(component component) { chararray = new boolean[127]; component.addkeylistener(this); } @override public void keypressed(keyevent e) { (possible synchronization lock?) int keychar = e.getkeychar(); if (keychar == 27 || keychar == 9 || keychar == 10 || keychar == 127) //useless keys del, tab, esc, etc.. keychar = 65535; if (keychar < 65535) //65535 represents no true char value chararray[keychar] = true; } @override public void keyreleased(keyevent e) { } @override public void keytyped(keyevent e) { } } import java.awt.dimension; import javax.swing.jframe; @suppresswarnings("serial") public class process extends jframe implements runnable { private boolean running; private input input; public process() { running = false; input = new input(this); settitle("keyboard test"); setsize(new dimension(200, 200)); tofront(); setdefaultcloseoperation(jframe.exit_on_close); setvisible(true); } /** * @param args */ public static void main(string[] args) { new process().startthread(); } public synchronized void startthread() { running = true; new thread(this).start(); } @override public void run() { while (running) { (possible synchronization lock?) (int = 0; < input.chararray.length; i++) { if (input.chararray[i] == true) { input.chararray[i] = false; system.out.println((char) i); } } try { thread.sleep(20); } catch (interruptedexception e) { } } } }
your chararray
variable accessed @ least 2 threads (the 1 start in process , edt in input class) need synchronize accesses ensure visibility (i.e. make sure changes made 1 thread visible other thread).
note there several other issues in code, example:
- you should not let escape during construction (by calling
input = new input(this)
orcomponent.addkeylistener(this)
) - can lead weird behaviour in multi-threaded environment - you should try have
jframe
variable insideprocess
class instead of extendingjframe
- i'm not sure how plan set
running
false, there no synchronization around variable inrun
method might not see become false.
Comments
Post a Comment