Java – use sleep () for a single thread
I'm new to Java and started using different threads to use wait () or sleep () on part of my code and keep other threads running
For this project, I use JFrame and javax swing.* And Java awt.* Import What I want to do is let one of the threads (which is the main and starting thread in my code) allow players to select a space on the tic tac toe board. When they click it, it will change the icon, and then the AI will wait for 1 second, and then play back from the second thread I created
Unfortunately, whenever I call Ait When sleep (1000) (AIT is my thread name), both threads will wait 1 second before completing execution Who can tell me why sleeping on one thread will prevent my whole execution?
Solution
To better explain, your swing GUI is created on its own special thread, which is separated from the running thread by main () and other code Create a swing component in the invokexxx block (even if you don't do so), your GUI will run on a single thread named initial thread. Now, if you just call sleep on the event dispatch thread (or on the same thread), it will wait for the thread The call to sleep is complete Now, because all swing events are processed on the EDT, we call sleep (..) To pause execution, thereby pausing the processing of UI events, so the GUI is frozen (until sleep (..) Return)
You should not use thread on event dispatch thread sleep(..) (or sleep will prevent unnecessary execution of any blocked threads), because this will cause the UI to appear frozen
Here is a good example, which accurately illustrates calling thread on EDT of GUI sleep(..) Causing this unnecessary behavior
Instead, use:
>Swing timer, for example:
int delay=1000;// wait for second Timer timer = new Timer(delay,new AbstractAction() { @Override public void actionPerformed(ActionEvent ae) { //action that you want performed } }); //timer.setRepeats(false);//the timer should only go off once timer.start();
> Swing Worker
Or if the swing component is not created / modified:
>TimerTask > thread, and then you will use thread Sleep (int milis) (but it is the last option of IMO anyway)
UPDATE
Swing timer / swingworker is only added in Java 1.6. However, TimerTask and thread have long sinusoidal Java 1.3 and JDK 1. Therefore, you can even use any of the above two methods and wrap the call to create / operate swing components in the swingutilities / eventqueue #invokexx block; This is the old way: P