简体   繁体   中英

Thread.sleep pausing whole program

I have a main form with a button, that when pressed, should start a new count-down timer thread.

This is the code in the button's action listener:

 Counter c = new Counter(timeToFinish);

This is the code for the Counter class:

class Counter implements Runnable {

        int waitingTime = 0;
        Thread myCounter = new Thread(this);

        public Counter(int waitingTime)
        {
            this.waitingTime = waitingTime;
            myCounter.run();
        }

        public void run(){

            //Start countdown:
            do  
            {

                waitingTime -= 1;

                try {

                    Thread.sleep(1000);
                    System.out.println(waitingTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while (waitingTime >= 0);

        }
    }

The problem is, when I create a new instance of the Counter class, it pauses the whole program, not just that thread. The problem must be with "Thread.sleep".

Because you are directly calling the run method.

Instead you should wrap it in a Thread and start the thread.

For eg, replace

myCounter.run();

by

new Thread(this).start();

Just because you call the run method from the Counter constructor. That's not how it works with threads. You'll have to remove this call, wrap the Runnable in a Thread instance and call start() on the thread:

 new Thread(new Counter(2)).start();

You aren't actually start() ing multiple threads.

The Thread.run() method simply runs the code associated with the thread, like any other normal function. It doesn't start a separate thread.

You need to call Thread.start() , to start a new thread and run your code in it.

You should use start() method of your thread. Use

c.start();

otherwise you have a class and you are invoking one of its methods, and of course it is running in main thread and sleeping the main thread.

You're calling run directly, it'll run in the current thread, and sleep the current thread, which I guess is the event thread. This cause the pause in your program.

You should use SwingUtilities class

see

http://www.java2s.com/Code/Java/Threads/InvokeExampleSwingandthread.htm

    // Report the result using invokeLater().
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        resultLabel.setText("Ready");
        setEnabled(true);
      }
    });
  }
};

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