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.

Similar Messages

  • Difference between LockSupport.parkUntil and Thread.sleep method

    Hi
    Could someone please explain the difference between LockSupport.parkUntil and Thread.sleep methods.
    Thanks in advance.

    javaLearner wrote:
    The thing that I am trying to understand is - the difference / correlation between the two methods mentioned.
    In the javadoc, there is a mention of correlation between the LockSupport methods park, unpark and the Thread methods suspend, resume - but not park and sleep.Then that suggests that there isn't any difference /correlation -- whatever you meant by that. Perhaps your question is like asking for the difference between a fish and a bicycle.
    Also, I would like to understand the statement
    These methods are designed to be used as tools for creating higher-level synchronization utilities, and are not in themselves useful for most concurrency control applications. (from the javadoc)Again, you're going to have to explain what you don't understand about it.

  • 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

  • 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

  • How to use Thread.sleep() with Java Berkeley Base API?

    Hi,
    I have explained the weird problem about the server was too busy to response to SSH but it continued to finish to run (Server not response when inserting millions of records using Java Base API
    Even I tried to increase CachSize and renice Java program, but it did not work. So, I am thinking to set sleeping time for threads in Java Berkeley Base API (using “ps” command, there were 18 light weight processes created). My program did not implement transaction or concurrency because it simply creates (millions) databases records only. Is it possible and correct to do like this in the code:
    try{
    //do create a db record
    Thread.currentThread().sleep(1000);//sleep for 1000 ms
    catch(ItrerruptedException ie){
    Thank you for your kindly suggestion.
    Nattiya

    where can I get the help doc about use AT commands in java.
    Can you give me some code example about this. It is
    difficulty to me to write it myself.You simply have to send the characters and receive the characters via the comm extension. Here is the ITU standard command set - http://ridge.trideja.com/wireless/atcommands/v250.pdf. Various modems and other devices extend this in a number of ways, you may need to find documentation specific to your device as well. But start with the standard.

  • Using Thread.currentthread.sleep but not delaying appropriately

    Ok, here it goes. Im currently using the thread.sleep method to delay the changing of the text within some labels. I have 3 labels which represent some arrays. I then sort the arrays. Im trying to throw a delay in so that the user can see the changes happen to the array. Although, when I call the wait.millisec(1000) in (the sleep function I threw into its own wait class) it seems that the waiting all happens at the end. I dont see it during the loop to show the arrangement changes within the arrays. I stepped through the code using the debugger, but it doesnt seem to help.
    Look in the buttonListener within the FourX class.
    * SortTest.java                                   Author:Tim Dudek
       This trivial program tests the insertion sort and selection sort
       subroutines.  The data is then shown graphically.
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    public class SortTest {
       final static int ARRAY_SIZE = 10;  // Number of items in arrays to be sorted.
                                            // (This has to be 10 or more.)
       public static int[] A, B;
       public static JLabel lblOrig, lblSS, lblIS;
       public static void main(String[] args) {
            JFrame frame = new JFrame ("Tim Dudek");
              frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
              FourX display = new FourX();//create the main panel
              frame.setSize(450, 320);
              frame.getContentPane().add(display);
              frame.setVisible(true);  
          A = new int[ARRAY_SIZE];     // Make an array  ints
          for (int i = 0; i < A.length; i++){      // Fill array A with random ints.
             A[i] = (int)(100*Math.random());
             lblOrig.setText(lblOrig.getText() + " "     + A);
    lblIS.setText(lblIS.getText() + " "     + A[i]);
    lblSS.setText(lblSS.getText() + " "     + A[i]);
    B = (int[])A.clone(); // make B an exact copy of A.
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    public class FourX extends JPanel {
         static final long serialVersionUID = 1L; //eclipse echo problem
         private JLabel lblO, lblI, lblS;
         private JButton sort;
         public FourX(){//JLabel lblOrig,JLabel lblSS, JLabel lblIS){
              setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
              SortTest.lblSS = new JLabel ("");
              SortTest.lblOrig = new JLabel ("");
              SortTest.lblIS = new JLabel ("");
              lblO = new JLabel("Orginal", JTextField.LEFT);
              lblI = new JLabel("Insertion Sort", JTextField.LEFT);
              lblS = new JLabel("Selection Sort", JTextField.LEFT);
              sort = new JButton("Sort");     
              sort.addActionListener(new buttonListener());
              SortTest.lblSS.setFont(new Font("Arial", Font.BOLD, 30));
              SortTest.lblSS.setHorizontalAlignment(JTextField.CENTER);
              SortTest.lblSS.setBorder(BorderFactory.createLineBorder (Color.RED, 3));
              SortTest.lblIS.setFont(new Font("Arial", Font.BOLD, 30));
              SortTest.lblIS.setHorizontalAlignment(JTextField.CENTER);
              SortTest.lblIS.setBorder(BorderFactory.createLineBorder (Color.BLUE, 3));
              SortTest.lblOrig.setFont(new Font("Arial", Font.BOLD, 30));
              SortTest.lblOrig.setHorizontalAlignment(JTextField.CENTER);
              SortTest.lblOrig.setBorder(BorderFactory.createLineBorder (Color.BLACK, 3));
              add(Box.createRigidArea(new Dimension (10, 10)));
              add(lblO);
              add(SortTest.lblOrig);
              add(Box.createRigidArea(new Dimension (10, 10)));
              add(lblS);
              add(SortTest.lblSS);
              add(Box.createRigidArea(new Dimension (10, 10)));
              add(lblI);
              add(SortTest.lblIS);
              add(Box.createRigidArea(new Dimension (10, 10)));
              add(sort);
         private class buttonListener implements ActionListener{
              public void actionPerformed (ActionEvent event){
              // sort A into increasing order, using selection sort
                   for (int lastPlace = SortTest.A.length-1; lastPlace > 0; lastPlace--) {
                        Wait.milliSec(50);
                   //Find the largest item among A[0], A[1], ... A[lastPlace],
              // and move it into position lastPlace by swapping it with
              // the number that is currently in position lastPlace
                        int maxLoc = 0; // location of largest item seen so far
                   for (int j = 1; j <= lastPlace; j++) {
                        if (SortTest.A[j] > SortTest.A[maxLoc])
                   maxLoc = j; // Now, location j contains the largest item seen
                   int temp = SortTest.A[maxLoc]; // swap largest item with A[lastPlace]
                   SortTest.A[maxLoc] = SortTest.A[lastPlace];
                   SortTest.A[lastPlace] = temp;
                   Wait.milliSec(100);//<------------ waiting???>
                   SortTest.lblSS.setText("");
                   for (int i = 0; i < SortTest.A.length; i++){
                        SortTest.lblSS.setText(SortTest.lblSS.getText() + " "     + SortTest.A[i]);
                   Wait.oneSec();//<------------ waiting???>
                   // sort the array A into increasing order
                   int itemsSorted; // number of items that have been sorted so far
                   for (itemsSorted = 1; itemsSorted < SortTest.B.length; itemsSorted++) {
                        // assume that items A[0], A[1], ... A[itemsSorted-1] have
                        // already been sorted, and insert A[itemsSorted] into the list.
                        int temp = SortTest.B[itemsSorted]; // the item to be inserted
                        int loc = itemsSorted - 1;
                        while (loc >= 0 && SortTest.B[loc] > temp) {
                             SortTest.B[loc + 1] = SortTest.B[loc];
                             loc = loc - 1;
                        SortTest.B[loc + 1] = temp;
                        Wait.milliSec(100);//<------------ waiting???>                    SortTest.lblIS.setText("");
                        for (int i = 0; i < SortTest.B.length; i++){
                             SortTest.lblIS.setText(SortTest.lblIS.getText() + " "     + SortTest.B[i]);
    public class Wait {
         public static void oneSec() {
              try {
                   Thread.currentThread().sleep(1000);
              catch (InterruptedException e) {
                   e.printStackTrace();
         public static void milliSec(long s) {
              try {
                   Thread.currentThread().sleep(s);
              catch (InterruptedException e) {
                   e.printStackTrace();

    Wow, ok. this is extrodinarily confusing. I read the tutorials, but they're not easy to follow.
    So, what I did was at the entry point:
    public class SortTest implements Runnable {
       final static int ARRAY_SIZE = 10;  // Number of items in arrays to be sorted.
                                            // (This has to be 10 or more.)
       public static int[] A, B;
       public static JLabel lblOrig, lblSS, lblIS;
       public static void main(String[] args) {
            (new Thread(new SortTest())).start();
       public void run(){
            JFrame frame = new JFrame ("Tim Dudek");
              frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
              FourX display = new FourX();//create the main panel
              frame.setSize(450, 320);
              frame.getContentPane().add(display);
              frame.setVisible(true);  
          A = new int[ARRAY_SIZE];     // Make an array  ints
          for (int i = 0; i < A.length; i++){      // Fill array A with random ints.
             A[i] = (int)(100*Math.random());
             lblOrig.setText(lblOrig.getText() + " "     + A);
    lblIS.setText(lblIS.getText() + " "     + A[i]);
    lblSS.setText(lblSS.getText() + " "     + A[i]);
    B = (int[])A.clone(); // make B an exact copy of A.
    Ok, as I understand, this creates the initial thread to build the gui. Now you suggest that when the user hits "sort" that a second thread be created to handle the sorting routine.  From what I understand I can only inherit from one class in java.  My buttonListener already implements ActionListener. I obviously cant implement ActionListener and Runnable.  Do you have a suggestion? Maybe a link to an example?
    I'm pretty lost. 
    Tim                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • How using sleep() method ?

    Hello every body and marry christmas for all :)
    I want to stop my program during 1 second, how can I do that and witch package must I use,
    thank you.

    try{
    //do what you want to do before sleeping
    Thread.currentThread().sleep(1000);//sleep for 1000
    00 ms
    //do what you want to do after sleeptig
    catch(ItrerruptedException ie){
    //If this thread was intrrupted by nother thread
    }Actually, since sleep is a static method, it's better form to just use Thread.sleep(1000) and skip the currentThread() part.

  • 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.

  • 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

  • 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

  • Troubles using Thread & repainting components at same time.

    Hi. I have a frame which contains several labels. If i clicked on a label, it runs a method which changes label's aspect. Then, i need that once passed a second, label's aspect changes to original aspect. The problem is that controls dont repaint while i use Thread.sleep(1000) method. I have tried to call repaint() (both frame and label) before calling Thread.sleep() but it doesnt work too.
    Any idea on how to solve this problem? Thanks for answers :)

    Well, it wasnt a layout problem.
    I've found solution trough camickr's link. Now im using Timer and TimerTask classes and all is working fine.
    Thank you very much :)

  • Contiunous running programs: Thread.sleep vs. Scheduled Tasks

    Hello,
    I have simulation programs that should run continuously for weeks at a time. I am seeking any advice or comments on the best way to do something like this.
    Some programs run every 30 seconds; others run once per hour; others run once per day. These programs involve simulating the use of a popular website by reading web pages and inserting records into Oracle 9i databases.
    As far as the "every 30 seconds" program, I use Thread.sleep to pause the program for each interval. Is this a good method?
    What about programs running once per hour or per day? I have used the Windows XP Scheduled Task program to execute the program. Is this a good method?
    Does anybody know of a better way to do such things?
    Any comments or helpful links are greatly appreciated.
    Thank you,
    Logan

    I have simulation programs that should run
    continuously for weeks at a time. I am seeking any
    advice or comments on the best way to do something
    like this.If you have a simulator, does it have to simulate time on a one to one basis. Could it not simulate 30 seconds, every 3 seconds and thus not need to run for the full week. If you have to run in real time, what are you simulating.
    Some programs run every 30 seconds; others run once
    per hour; others run once per day. These programs
    involve simulating the use of a popular website by
    reading web pages and inserting records into Oracle
    9i databases.
    As far as the "every 30 seconds" program, I use
    Thread.sleep to pause the program for each interval.
    Is this a good method?No. Sleep for 30 seconds just means there is atleast 30 seconds delay from the end of the last task to the start of the next task. This could means every 30.1 seconds or even every 33 seconds depending on how long the task takes to run.
    If you create a single ScheduledExecutorService you can run a task with any period you suggest with a dynamic number of threads.
    e.g.
    Execuotrs.newScheduledThreadPool(1);
    >
    What about programs running once per hour or per day?See previous.
    I have used the Windows XP Scheduled Task program to
    execute the program. Is this a good method?If it is a couple of times per day or per week this is a good choice.
    >
    Does anybody know of a better way to do such things?see previous.

  • 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

  • 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?

  • Repaint() being delayed by Thread.sleep()

    Hello, I am programming a Memory-like card game, where the user picks cards and if they match they stay flipped over, but if they don't match the cards will be displayed for a second and then flipped back over. However, I am running into a problem when the cards do not match, the game will wait (using Thread.sleep()) and then flip the cards back over. The problem is that the second card picked, that is determined to not be a match, is not showing the face before the cards are returned to the hidden state. I think that it is being flipped twice in a row at the end of the sleep(), therefore never actually displaying the front of the card. I have tried putting repaint() everywhere, and there is one before the sleep(), but it still doesn't seem to work properly. Here is the code for my mouse clicked event. Thanks for any help!
      public void mouseClicked(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        Card temp = null;
        for (int i = 0; i < 52; i++) {
          temp = cards.getCard(i);
          if (temp.contains(x, y)) {
            if (temp.isFront() == true)
              return;
            temp.swapImg();
            this.repaint();
            if (flipped == null) {
              flipped = temp;
            } else {
              if (temp.getVal() == flipped.getVal()) {
                // we have a pair
              } else {
                // cards don't match.. start over
                try {
                  Thread.sleep(500);
                } catch (InterruptedException ie) {
                  System.out.println("Thread was interrupted!\r\n");
                temp.swapImg();
                flipped.swapImg();
              flipped = null;
            break;
      }

    Don't use Thread.sleep() inside a Listener. You are blocking the EDT which prevents the GUI from repainting itself.
    Use a Swing Timer to schedule the flipping of the cards.

Maybe you are looking for

  • How do I import music files from a flash drive to my iTunes library on my laptop

    How can I import music files from a flash drive to my iTunes library? I put the flash drive into my laptop, selected " add file to library", selected the songs I wanted from the flash drive, and it looked like they were added as the names show under

  • My iphone no longer provides a functional personal hotspot via usb or bluetooth, how do I fix this?

    I am currently running a 3gs (never jailbroken or unlocked) with ios 5.1.1. The computer I am connecting it to is a Macbook Pro Early 2011 15". I am in Canada with Rogers as a telecommunication provider. I do have plenty of data and have used this fe

  • Airport Wirless Router Linksys

    have a wireless Linksys router that I put a 128 bit encryption. It was driving me mad that when booted up in OS 9 I could not use my password. I tried using the entire 24 character code as a password, and it works. That is how you use 128 bit encrypt

  • HT1766 I am unable to sync my device apps back to my laptop

    I know that apple has removed the "sync" check box for apps - however highlighting all the apps on the phone display on the computer then pressing apply/sync seems to work.... i have software issues with my iphone and wish to rerstore it and start ag

  • Installed new battery. Not working right?!?!

    I bought a battery from battery plus for my Macbook Pro 13" Early 2011. I installed it and it wouldn't turn on. So I figured it just wasn't charged, I plugged in the charger and it turned on. Great!! Not really. I noticed the battery symbol in the st