Thread.sleep() behaves weird in Listeners

Hey,
I am a rookie in Swing and I am writing a small game. The game is a two player game. I am now trying to add AI to the game so when the human player clicks on the board he plays and then the computer plays its turn.
So in pseudo code:
//in action listener
human.play
robot.proceed
sleep(3000)
reprint the board
robot.proceed
sleep(3000)
reprint the board
robot.proceed
sleep(3000)
reprint the board
where proceed is a method that makes the robot play on three stages...
So basically I am trying to simulate the actual way a human plays...
The problem is that when the human player clicks the game hangs for all 9 seconds then suddenly the board is reprinted with both moves...
How can I overcome this problem?
Thank you

first of all, take the time to read the documentation, at least the basics.
secondly, never sleep in a GUI-component method, because then the GUI will not be updated until the sleep is over (just what you see).
create a separate thread for sleeping and updating your board and let the GUI repaint as needed.
thomas

Similar Messages

  • Thread.sleep takes a lot of CPU time!

    Hi,
    I have the run method like this:
    public void run()
    while(true)
    //some set of operations
    Thread.sleep(5*1000*60);
    The above code's performance was measured under stress test. . The sleep operation seems to take a lot of CPU time
    though ideally sleep is like a no-operation mode, meaning since no operation
    is done when a thread sleeps, it should not use any/minimal CPU time.
    But it seems to take over 30% of CPU time!
    Any ideas on why such a weird thing's happening?
    In fact, in one more similar method also, sleep is taking similar CPU
    time.

    A sleeping thread uses no CPU. Try the following, both with and without the for loop. If you see a constant high CPU usage, even when the thread is sleeping, it's probably that the CPU usage is measured as an average over the last second or several seconds, so when the tasks you're performing are intense and take a significant fraction of the time you're sleeping, the average CPU usage doesn't go down that much.
    public class Sleeper {
        public static void main(String[] args) throws Exception {
            while(true) {
                for (int ix = 0; ix < 100000000; ix++) {
                    int jx = ix * 2;
                    ix = --jx;
                Thread.sleep(5 * 1000* 60);
    }

  • Macbook behaving weird

    Hi all!
    For the last two or three weeks i've seen how my mac is behaving weird, it's taking longer to load, i have 4 widgets running and prior to this they were using only 5% of ram now 10%, i can take this but today it crashed twice
    also i almost daily put it to deep sleep but lately is crashing when i awake it
    I don't know what to do, any help is well recevied
    Thanks in advance for your support
    Message was edited by: Ginda000

    "AppleJack" http://www.versiontracker.com/dyn/moreinfo/macosx/19596

  • Thread is behaving differently on different machines??

    Hi
    I am developing a Java Swing application, which launches an external exe.
    Then I am using a Thread to monitor whether the launched exe is running or terminated abruptly by using its PID. If it terminates then the thread shows a msg box.
    Everything works fine in my machine and in few other machines.
    But the same thread stop abruptly on some other machines... and displays the msg box even though the exe is running correctly.
    And I heard thread behaves differently on different CPUs'.
    How to handle this situation??
    Please help.
    This is my code:
    public class SolverPoller implements Runnable
            String solver = null;
            int PID;
             * Constructor to initialise the Thread
             * @param programName - Solver execuatable name
             * @param pid - Process ID of the running solver
            SolverPoller(String programName, int pid)
                solver = programName;
                PID = pid;
                //reset the blnClosedAbruptly
                blnClosedAbruptly = false;
            public void run()
                File deleteFile = null;
                try
                    //if the stored PID and refreshed are same
                    //Continue waiting
                    while(checkPIDOfSolver(String.valueOf(PID), solver))
                        //sleep for a sec
                        Thread.sleep(1000);
                    //When the solver process terminates
                    //interrupt ProgressBarIncrementer Thread
                    inc.interrupt();
                    if(Delia.getProcessorType() == 'T')
                        deleteFile = new File("TIP3DSolver.res");
                    else if(Delia.getProcessorType() == 'S')
                        deleteFile = new File("SPLITVISSolver.res");
                    if(!deleteFile.exists())
                        //set it to true, indicating solver terminated abruptly
                        blnClosedAbruptly = true;
                        progressBar.setValue(0);
                        progressBar.setStringPainted(true);
                        progressBar.setString("0%");
                        progressBar.repaint();
                        JOptionPane.showMessageDialog(DentonIntegratedToolApp.getDentonInstance().getFrame().getContentPane(), "Solver terminated abruptly!", "Solver Error", JOptionPane.ERROR_MESSAGE);
                catch(InterruptedException ie)
                catch(Exception e)
                finally
                    deleteFile = null;
        }Praveen

    I'm not sure if this matters, but it appears that you are calling Swing methods off of the EDT beginning with "progressBar.setValue(0);". What happens if you wrap those calls in a Runnable and call them with SwingUtilities.invokeLater(...)?

  • What's wrong to put Thread.sleep in a session bean?

    i am working on a trading platform and i think there is a design flaw. The part i am working on is the Order Management module. When an order value object is published to a JMS topic and picked up by a MDB. The MDB, in turn, calls a session bean (could be stateless, I didn't check), OrderEngineBean. After this bean saves the order vo into database and broadcast the message to all involved parties, it suspends for 12 sec, using Thread.sleep, so other parities might have a chance to update the vo. If no update occurs, the order is considered expired and abandoned.
    It looks awkward to me to use a Thread.sleep in a session, but I haven't come out with a better idea to deal with the scenario like above.
    Anyone can help me out?
    Thanks a lot!
    Sway

    Setting the property "max-beans-in-free-pool" is not the answer to this issue. By setting this property to 1, the container merely instantiates and keeps one instance of the bean in the free pool at the "start" of the app server. But if the container comes across more than one requests for the same EJB simultaneoulsy, then it will create new instances at that time to handle the requests simultaneously.
    You are seeing intermixed log messages between two threads because these messages are being logged from two different instances of the EJB and NOT the same instance of the EJB. The container does synchronizes the calls on "a method" on "a instance". So what you are seeing are the messages coming from "a method" on "two different instances" of the same EJB.
    You can refer to the EJB 2.0 specification section 6.11.6 Non-reentrant instances for details about simultaneous access to the same session object.

  • Work manager using thread.sleep or delay doesn't work

    Hi all,
    I used Spring framework and oracle weblogic 10.3 as a container.
    I used workmanager for manage my thread, I already made one thread that managed by workmanager. Fortunately spring provide the delegation class for using workmanager, so I just need to put it on applicationContext.xml.
    But when I put the "while" and TimeUnit for sleep the process on desired delayed time, the deployment process never finished. It seems the deployment process never jump out from while loop for finishing the deployment.
    Why?, As I know using typical thread, there is no issue like this. Should I use another strategy for make it always loop and delay.
    This is my simple code :
    import java.util.concurrent.TimeUnit;
    import org.springframework.core.task.TaskExecutor;
    public class TaskExecutorSample{
         Boolean shutdown = Boolean.FALSE;
         int delay = 8000;
         TimeUnit unit = TimeUnit.SECONDS;
         private class MessageGenerator implements Runnable {
              private String message;
              public MessageGenerator(String message){
                   this.message = message;
              @Override
              public void run() {
                   System.out.println(message);
         private TaskExecutor taskExecutor;
         public TaskExecutorSample(TaskExecutor taskExecutor){
              this.taskExecutor = taskExecutor;
              try {
                   while (shutdown.equals(Boolean.FALSE)){
                        this.printMessage();
                        unit.sleep(delay);
              } catch (Exception e) {
                   System.out.println(e.getMessage());
         public void printMessage() {
              taskExecutor.execute(new MessageGenerator("Print this Messages"));
    Really thanks in advance.
    Regards,
    Kahlil
    Edited by: Kahlil on May 26, 2010 2:38 PM
    Edited by: Kahlil on May 26, 2010 2:42 PM

    Hi,
    i m not sure whether it's an issue with Spring or not. But i tried using Thread.sleep(1000) in a Simple webapplication to see Workmanagers works properly or not. I found that it works extremely great: http://weblogic-wonders.com/weblogic/2010/01/24/workmanager-at-webapplication-level/
    Thanks
    Jay SenSharma

  • Problem with Thread.sleep()

    hi all,
    I am trying Thread.sleep() method to introduce a delay. In the program i ask the user to specify the value to be entered in Thread.sleep() (to indicate the amount of delay desired by the user). but strangely, if a low value is entered, i get a different result which actually should not happen as the rest of the calculation remains the same, only the amt of delay changes.
    could anyone help me with this
    cheers
    ankit

    [url http://forum.java.sun.com/thread.jsp?forum=31&thread=536288]Double-post

  • Using Thread.sleep()

    When I put Thread.sleep() in my code, the debugger says I need to catch it. How do I do that?

    But in general, you don't want to just smother exceptions like that. It's okay when you're sleeping (or can be) because often if you're interrupted, you want to just ignore it and move on. However, there's more to handling exceptions than just an empty catch block.
    http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html

  • Mouse events during Thread.sleep

    hi.
    I have an applet .
    I have a alghoritm simulator.
    Everytime I find a solution I call the method Thread.sleep .
    I want to pause the application and I create a JToggleButton Pause .
    When I press the Pause during sleep mouse event are managed at the end of alghoritm.
    How can I manage mouse events during sleep?

    All UI events (such as mouse events) occur on the event dispatch thread (EDT).
    That means if you sleep on the EDT, you lock up the UI. For this reason, you shouldn't be sleeping on the EDT.
    I'm not sure what your sleep is trying to do but you need to manage your threads a little more carefully. For instance, any time consuming process which is invoked as a result of a UI event needs to be fired on a new thread to prevent the UI freezing. The fun starts when you have to update the UI as a result of that process, because you should then hook back onto the EDT to avoid the risk of deadlock.
    Some utility classes are provided, such as SwingUtilities, and other example code is provided on Sun's site, such as SwingWorker - but if you do much UI work you'll probably end up with your own core set of threading tools and so on to make life easier.

  • Can LabVIEW threads sleep in increments less than a millisecon​d?

    I am aware of two LabVIEW sleep functions:
    1) All Functions | Time & Dialog | "Wait (ms)"
    2) All Functions | Time & Dialog | "Wait Until Next ms Multiple"
    In this day and age, when 3GHz processors sell for less than $200, it seems to me that a millisecond is an eternity. Is there any way to tell your LabVIEW threads to sleep for something less than a millisecond?
    In Java, the standard Thread.sleep() method is written in milliseconds [sorry, the bulletin board software won't let me link directly]:
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/​Thread.html#sleep(long)
    but there is a second version of the method that allows for the possiblity of nanoseconds:
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/​Thread.html#sleep(long, int)
    So there does seem to be some consensus that millisecond sleep times are getting a little long in the tooth...

    Hi Tarheel !
    May be you should get some idea of the kind of timing accuracy that you can reach when using a loop.
    Use the attached vi, which runs repeatedly a For loop (10 iterations) reading the time, then calculate the average and standard deviation of the time difference between the loop iterations.
    On my PC (P4, 2.6 MHz, W2K), I get a standard deviation of about 8 ms, which appears to be independent of the sleep duration I asked for.
    Same thing with a timed loop.
    Under MacOS X (PowerBook, 1.5GHz), the SD falls down to 0.4 ms.
    I tried to disable most of the background processes running on my PC, but I could not get a better resolution.
    Seems that the issue is not in LV but on the way the OS manage its internal reference clock.
    Since you are a Java afficionado, may be you could produce something equivalent ?
    A proof that nanosecond resolution is available on a PC could be of great help to NI. Why bother with costly timers on DAQ cards ?
    By the way, it took me about one minute to create the attached vi. I would like to have an idea of the time required to do the same thing in Java.
    Tempus fugit...
    CC
    Chilly Charly    (aka CC)
             E-List Master - Kudos glutton - Press the yellow button on the left...        
    Attachments:
    Timing precision.zip ‏11 KB

  • Java Thread.sleep() on Windows 8 stops in S3 sleep status

    There's a desktop application that uses Thread.sleep() to achieve long (minutes or hours) delays. This same application has been working fine from Windows XP through Windows 7. The application calculates how far in the future it needs to do something, then hits a Thread.sleep(msToWait). This has been working fine, even if the system happens to go into S3 or S4 sleep state during the wait.  All is good as long as the machine is awake at the time when the sleep expires.
    As of Windows  8 (and 10), though, the code after Thread.sleep() does not execute "on time" if the machine has been in S3 during the sleep interval. It appears that the machine begins executing code at "msToWait" plus the time the machine has been in S3.
    Earlier versions of Windows did not exhibit this behavior; code after Thread.sleep() waited the right amount of time, irrespective of sleep status.
    A test program and procedure were developed. The procedure is to 1) run the program, 2) cause the machine to sleep for about a minute, then 3) wake the machine and wait for the program to finish.
    If this the program is run on Windows 10 (reporting as 8) with JVM Version: 25.40-b25, it fails (the 63589 corresponds to the minute that the machine was in S3):
    C:\Users\Tester\Downloads>SleepTester.exe
    Wed Apr 01 10:47:35 PDT 2015 Using default number of minutes: 5
    Wed Apr 01 10:47:35 PDT 2015 You can use "SleepTester -minutes 10" to have it sleep for 10 minutes, for example.
    Wed Apr 01 10:47:35 PDT 2015 JVM Version: 25.40-b25 Windows Version: Windows 8
    Wed Apr 01 10:47:35 PDT 2015 The program will now wait for 5 minutes.  Expect wrap-up at Wed Apr 01 10:52:35 PDT 2015
    Wed Apr 01 10:53:38 PDT 2015 The system has come through the Thread.sleep(300000).
    Wed Apr 01 10:53:38 PDT 2015 This should be a low number: 63589
    Wed Apr 01 10:53:38 PDT 2015 This appears to be operating incorrectly...the expected sleep time has NOT been achieved.
    Wed Apr 01 10:53:38 PDT 2015 Program is ending.
    If the process is run on Windows 7, it does not fail:
    Wed Apr 01 17:12:18 EDT 2015 Java Runtime Version: 1.8.0_31-b13 JVM Version: 25.31-b07 Windows Version: Windows 7
    Wed Apr 01 17:12:18 EDT 2015 The program will now wait for 6 minutes.  Expect wrap-up at Wed Apr 01 17:18:18 EDT 2015
    Wed Apr 01 17:18:18 EDT 2015 The system has come through the Thread.sleep(360000).
    Wed Apr 01 17:18:18 EDT 2015 This should be a low number: 0
    Wed Apr 01 17:18:18 EDT 2015 Program is ending.
    This is the guts of  test program:
    [code]
    public static void main(String[] args) throws Exception {
       System.out.println(new Date() + " Java Runtime Version: " + System.getProperty("java.runtime.version") + " JVM Version: " + System.getProperty("java.vm.version") + " Windows Version: " + System.getProperty("os.name"));
       long msDelay = mMinutes * 60 * 1000;
       long wakePoint = new Date().getTime() + msDelay;
       System.out.println(new Date() + " The program will now wait for " + mMinutes + " minutes. Expect wrap-up at " + new Date(wakePoint));
       Thread.sleep(msDelay); // If the machine goes into S3 during this interval, it should not matter, as long as it's awake when it fires.
       System.out.println(new Date() + " The system has come through the Thread.sleep(" + msDelay + "). ");
       long msAccuracy = Math.abs(new Date().getTime() - wakePoint);
       System.out.println(new Date() + " This should be a low number: " + msAccuracy);
       if (msAccuracy > 1000) System.out.println(new Date() + " This appears to be operating incorrectly...the expected sleep time has NOT been achieved.");
       System.out.println(new Date() + " Program is ending.");
    [/code]
    Was the change in behavior from earlier versions of Windows intentional?  Is it something that the JVM is controlling, or is there a difference in the underlying OS that is beyond the control of the JVM?

    I might need to create a work-around whereby I maintain a watch of the msDelay and the system clock.  If there is a discontinuity (which would only happen on Windows 8 or higher), then I would repair the msDelay value.
    A separate (but related) question:
    Can I conclude that since older JVM's running on Windows 8 still have the problem, that it's a Windows issue, and not a JVM issue?

  • Thread.sleep() issue

    Hi,
    It seems that Thread.sleep is inaccurate :
    Date d1 = new Date();
    try {
         Thread.sleep(200);
    } catch (InterruptedException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
    Date d2 = new Date();
    System.out.println(d2.getTime() - d1.getTime());
    I ran this multiple times and it returns me either 187 or 188 either 203 or 204
    Is there any explanation about this ?
    Thank you

    If you read the docs for sleep(), you'll see it says, "Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers." On Windows, the system clock is only accurate to about 10-15 ms.

  • Replace the wait with java embedding thread.sleep() function

    Hi,
    How to replace the wait with java embedding thread.sleep() function. Can anyone help.
    Thanks.

    drag and drop the java embedding component
    include the following code in it.
    try{ 
    Thread.sleep(60000);
    }catch(Exception e)
    --Prasanna                                                                                                                                                                                                                                                                                                                           

  • Confusion using Thread.sleep() method

    I tried it in this program
    class NewThread implements Runnable {
      String name; // name of thread
      Thread t;
      NewThread(String threadname) {
        name = threadname;
        t = new Thread(this, name);
        System.out.println("New thread: " + t);
        t.start(); // Start the thread
      // This is the entry point for thread.
      public void run() {
        try {
          for(int i = 5; i > 0; i--) {
            System.out.println(name + ": " + i);
            Thread.sleep(1000);
        } catch (InterruptedException e) {
          System.out.println(name + "Interrupted");
        System.out.println(name + " exiting.");
    class MultiThreadDemo {
      public static void main(String args[]) {
        new NewThread("One"); // start threads
        new NewThread("Two");
        new NewThread("Three");
        try {
          // wait for other threads to end
          Thread.sleep(10000);
        } catch (InterruptedException e) {
          System.out.println("Main thread Interrupted");
        System.out.println("Main thread exiting.");
    }the output is
    one: 5
    two: 5
    three 5
    delay of 1 second
    one:4
    two: 4
    three: 4
    delay of 1second
    what all i know about sleep() is that it pause the currently executing thread for specified time. hence in above program when first thread runs and prints value 5 then it should get paused for 1 second cause there is Thread.sleep(1000) after println() statement.
    and output should be
    one: 5
    delay of 1 second
    two: 5
    delay of 1 second
    three: 5
    delay of 1 second
    but this is not actually happens. may be i am wrong about Thread.sleep method() or something else.
    would you guys please clear it?
    regards
    san

    Thread.sleep() only sleeps the current thread. As each thread runs concurrently they all print concurrently and all sleep concurrently.

  • Alternative to Thread.Sleep in catch?

    Is there any other way to make the code wait than using Thread.Sleep in catch, because Thread.Sleep disturbs other objects on my form. Here is what I'm trying to do:
    Try{
    //do something
    catch
    // wait 10 seconds
    //retry

    Timers are a bit of a nuisance what with keeping your form in memory even when you try and dispose the things.
    You could push the thing you're doing onto another thread.
    Use async await.
    You could then use Task.Delay.
    A very simplified example:
    private async void Button_Click1(object sender, RoutedEventArgs e)
    await Task.Delay(2000);
    // Do something
    Because that's an async method processing returns to the caller when it hits the await.
    That then pauses 2 seconds without impinging on your UI thread.
    Before the separate thread continues with the code after your await.
    You could put your try catch into a method like that and it'd do what you want without a timer.
    10 seconds seems a bit of a short time by the way.
    Hope that helps.
    Recent Technet articles:
    Property List Editing ;  
    Dynamic XAML

Maybe you are looking for

  • ADOBE Reader issues with Macbook Pro

    Was trying to view a pay document from my HR site and it said Iwas missing Adobe Reader plug in. I have it downloaded - twice and still no luck. The Adobe reader is in my applications, but the website can not seem to use it.

  • How to connect my laptop to the internet using my iphone?

    Hello, I've just change from my former Nokia N95 to the iphone 4 (on Tmobile Germany) and I'm totally thrilled because this new device is just fantastic! However, I could easily connect my macbook via bluetooth to connect to the internet occasionally

  • DESPERATE! IPOD NOT SHOWING IN ITUNES WITH WINDOWS VISTA.

    I recently bought a new Dell Dimension E520 which came with windows vista pre installed. I seem to be one of many people having problems with it! Newest version of Itunes (7.1) is installed and working fine. When I plug my IPOD nano in however nothin

  • List of devices supported by ADF mobile

    Hi there, Does anyone know where I can find the latest list of devices currently supported by the latest release of ADF mobile? Thanks in advance. ET

  • Validating DTD with sequence embedded into choice

    Hey there! I have a validation problem. My XML file is coming with a DTD specifying that the element choice has the following structure (look at target and resource - I want both of them or one of them only, and that's my solution): <!ELEMENT choice