warbio
warbio

Reputation: 466

problem with threading JAVA

I'm trying to make so that when I press a button the program starts a method in a new thread. The problem is that when I press the button the program freezes until the method is done running like i didn't use a thread at all. Does anyone know how to solve this problem?

Thanks Morgan.

public Listeners()
{
  Calendar.ButtonAddReminder.addActionListener(new ButtonAddListener());
}

private class ButtonAddListener implements ActionListener
{
  public void actionPerformed(ActionEvent e) {
      new Thread(Calendar.reminder.Reminderchecker(Calendar.reminder.addReminder(date, str))) .start();
  }
}

Upvotes: 0

Views: 136

Answers (3)

Christopher
Christopher

Reputation: 704

Assuming that your Calendar class implements Runnable or extends Thread you should not call Calendar.reminder.Reminderchecker(Calendar.reminder.addReminder(date, str )) before starting the new Thread as this calls the run() method of the new thread.

Instead do something like that:

public class Calendar implements Runnable {
    public void run() {
        this.reminder.Reminderchecker(Calendar.reminder.addReminder(date, str ));
    }    
}

Upvotes: 1

Ben
Ben

Reputation: 2388

You need to make sure that all this happens in the new thread:

Calendar.reminder.Reminderchecker(Calendar.reminder.addReminder(date, str ))

At the moment

Calendar.reminder.addReminder(date, str )

and

Calendar.reminder.Reminderchecker()

are called on the Event Dispatching Thread before the new Thread is constructed and started.

The simplest way to correct this is to create a new Runnable object that carries out all of these steps, and then pass that to the new thread. I guess the returned object from Reminderchecker() is itself a Runnable, in which case you need something like this:

Runnable task = new Runnable() {
    public void run() {
        Runnable r = Calendar.reminder.Reminderchecker(Calendar.reminder.addReminder(date, str ));
        r.run();
    };
new Thread(task).start();

Upvotes: 1

Ryan Stewart
Ryan Stewart

Reputation: 128779

From that, it looks like something in Calendar.reminder.addReminder() or Calendar.reminder.Reminderchecker() is taking some time and locking up the UI since that's what's happening in the EDT.

Edit: Oh, I see. You're not doing what you think you're doing. You're executing Reminderchecker in the current thread. The Runnable returned by that method is what's getting executed in the new thread. To run Reminderchecker in a thread, do something like:

new Thread(new Runnable() {
    public void run() {
        Calendar.reminder.Reminderchecker(...);
    }
}).start();

Better: Don't spawn your own random threads like that. Use an organized concurrency strategy such as provided by an ExecutorService. The Executors class lets you easily create several that cover common uses.

Still better: Check out the SwingWorker and it API docs.

Upvotes: 4

Related Questions