简体   繁体   中英

Thread priority in Java

I am having problems in my application, that sometimes when both threads are moving mouse to some (X,Y) coordinates of the screen, threads would sometimes try to do that at the same time (to different (X,Y)), resulting in a zig-zag lasting for a few seconds.

Will changing thread priority of one of my threads to higher solve this problem, or should I add an AtomicBoolean in order to solve this problem? (The problem with AtomicBoolean is that, I would need an AtomicBoolean for many, many things, since in both threads there are many different functions invoking mouse movement)

If you are using a single mouse object between multiple threads, they should use a synchronize{} block on the section that should be handled in one shot. Other threads that need that object will then wait if they reach a similar synchronize block.

run() {
    synchronize (mouse) {
      mouse.move();
      mouse.click();
      mouse.move();
      etc();
    }
    otherStuff();
}

Just make sure your synchronize block is not so big that one thread monopolizes the time using the mouse. What that looks like depends on your application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM