Search code examples
javasleepwaitnotifyjprogressbar

Thread, Wait, Notify, Sleep in Java


I am developing/developed a desktop application, where the button has actionlistener and to do lot of background task, I didnt use the thread, wait, notify or sleep before. I am just confused which one to learn and which one to use otherwise when i click the button, the JFrame just freezes.

1) Could someone suggest me what to use and easier?

2) I am using jprogress bar with setvalue(n) method, but I would like to replace the n automatically with the time taken to load, How can I do this?


Solution

  • 1) You need to move your code running when you click your button into a new thread. Something like this will work:

    public class Worker implements Runnable {
        Thread t;
        public Worker() {
            t = new Thread(this);
        }
        @Override
        public void run() {
            //do stuff here
        }
        public void start() {
            t.start();
        }
    }
    

    Then when you click your button in your JFrame:

    Worker w = new Worker();
    w.start();
    

    2) You can call setProgress() with any int (eg, at the start get current time, at the end get current time, time taken = end-start) you want. Just make sure you have used setMaximum() too.