Should input listeners be synchronized?

前端 未结 2 1645
说谎
说谎 2021-01-16 06:55

My sample code posted below shows two classes. One implements KeyListener and the other implements Runnable and is running in an infinite loop sleeping every 20 ms. When a k

相关标签:
2条回答
  • 2021-01-16 07:35

    Your charArray variable is accessed from at least two threads (the one you start in Process and the EDT in your Input class) so you need to synchronize those accesses to ensure visibility (i.e. make sure that changes made by one thread are visible from the other thread).

    Note that there are several other issues in your code, for example:

    • you should not let this escape during construction (by calling input = new Input(this) or component.addKeyListener(this)) - this can lead to weird behaviour in a multi-threaded environment
    • you should try to have a JFrame variable inside your Process class instead of extending JFrame
    • I'm not sure how you plan to set running to false, but there is no synchronization around that variable in your run method so you might not see it become false.
    0 讨论(0)
  • 2021-01-16 07:39

    When it comes to AWT or Swing the number one rule is do not ever synchonize or otherwise interfere with the dispatch thread. If you're not familiar with this then take a look at Dispatch Thread Issues

    In your case I would separate the non GUI thread functionality into a separate class altogether - and use one of the really useful classes in java.util.concurrent to communicate between the two if necessary.

    If you get a lock or delay due to threading issues and you're actually in the Dispatch Thread whole GUI will freeze

    0 讨论(0)
提交回复
热议问题