DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   Java (http://www.daniweb.com/forums/forum9.html)
-   -   Multiple threads (http://www.daniweb.com/forums/thread201045.html)

adyopo Jul 1st, 2009 6:11 pm
Multiple threads
 
Ok, so my problem is this: I did a little java program to take the number of seconds from a text box and sleep a thread for that amount of seconds. Just to make it clear, here is the piece of code I used:
jTestare.addActionListener(new ActionListener() {
                                        public void actionPerformed(ActionEvent evt) {
                                                try {
                                                        Thread.sleep((Integer.parseInt(getStringInterval())));
                                                } catch (InterruptedException ex) {
                                                        ex.printStackTrace();
                                                }
                                                getLblReprGrafica().setOpaque(true);
                                                getLblReprGrafica().setBackground(Color.RED);
                                                getLblProcent().setText("100%");
                                        }
                                });
Now my problem is how can I make this piece of code shared by a bunch of buttons (without them interfering with one another, like in starting one thread, moving two text boxes to the right, inputing a value then hitting Run on the respective button, and so on). I don't know if this can be done, but it was given to me as an assignment a couple of years ago and I only did it with one thread.

di2daer Jul 1st, 2009 6:47 pm
Re: Multiple threads
 
Im not sure I understand your question, but anyway...
First of all, it looks like you're sleeping the main thread, which will cause your application to freeze for a number of seconds.
I might be off here but do you want to fire a new thread for each button but avoid write reduntant code? If so, then create a class that extends Thread and fire it with method start()

public class MyThread extends Thread {
  public MyThread(/*argument here if needed*/) {
  }

  public void run() {
    try {
    Thread.sleep(sleepTime);
    }catch(InterruptedException ie) {
    }
    // Do something here
  }
}

fire the thread like:
new MyThread().start();

adyopo Jul 2nd, 2009 2:50 pm
Re: Multiple threads
 
Thanks di2daer, I'm gonna try to modify my code accordingly and see what happens.


All times are GMT -4. The time now is 1:12 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC