Put the Java Threading Class in a separate class

Consider the 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 highlight an inline specific class?

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

I want to define a separate class that updates the table in the same way as here. How to transfer the list back to the table? Code example?

+2
source share
3 answers

Just create classthat extends Thread.

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

and create it like this:

Task task = new Task();

However, normal practice is to implement Runnable:

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

, Thread, , Callable<T>, T .

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

ExecutorService.

+5

, Thread. , , Runnable :

public class YourTask implements Runnable
{
    private ResultClass result;

    public void run() { }

    public ResultClass getResult() { return result; }
}

java.util.concurrent FutureTask. , .

+4

You can work with transfer parameters or set globally visible attributes, for 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);
  }
}
+1
source

Source: https://habr.com/ru/post/1736871/


All Articles