views:

61

answers:

3

Consider following SWT code example:

http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet151.java?view=co

How can I separate the inline defined class?

Thread thread = new Thread() {
        public void run() {
            ...
        }
    };

I want to define a separate class which updates the table just like it does here. How do I pass the list back to the table? Example code?

+5  A: 

Just create a class which extends Thread.

public class Task extends Thread {
    public void run() {
        // ...
    }
}

and create it as follows:

Task task = new Task();

The normal practice is however to implement Runnable:

public class Task implements Runnable {
    public void run() {
        // ...
    }
}

Or if you want a Thread which returns a result, implement Callable<T> where T represents the return type.

public class Task implements Callable<String> {
    public String call() {
        // ...
        return "string";
    }
}

Both can be executed using the ExecutorService.

BalusC
Damn, I type too slowly...
Smalltown2000
Don't subclass Thread. Implement Runnable.
Thilo
That's indeed a better practice, or maybe even `Callable<T>` if you want a result. That was however not his question.
BalusC
+1  A: 

You can work passing parameters or setting globally visible attributes, example:

class Foo
{
  public static String baz = "baz";
  private String bar = "bar";

  void startThread()
  {
    MyThread thread = new MyThread(bar);

    thread.start();
  }
}

class MyThread extends Thread
{
  String ref;

  MyThread(String ref)
  {
    this.ref = ref;
  }

  public void run()
  {
    // it can work with passed parameter
    System.out.println(ref);

    // but also with globally visible variables
    System.out.println(Foo.baz);
  }
}
Jack
+4  A: 

I would not create a class that extends Thread. It's more likely that you'll have a class that implements Runnable and provides access to private data members:

public class YourTask implements Runnable
{
    private ResultClass result;

    public void run() { }

    public ResultClass getResult() { return result; }
}

Have a look at java.util.concurrent packages and the new FutureTask. I think that's a better bet.

duffymo
If you want to return a result, also consider Callable instead of Runnable.
Thilo