Reputation: 9813
Consider following SWT code example:
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?
Upvotes: 2
Views: 1455
Reputation: 1108712
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
.
Upvotes: 5
Reputation: 308763
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.
Upvotes: 4
Reputation: 133577
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);
}
}
Upvotes: 1