将Java线程处理类放到单独的类中 [英] Put Java Threading Class into a separate class

查看:79
本文介绍了将Java线程处理类放到单独的类中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下SWT代码示例:

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?

推荐答案

只需创建一个class其中extends Thread.

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

并按如下所示创建它:

Task task = new Task();

但是,通常的做法是实施 :

The normal practice is however to implement Runnable:

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

或者如果您想要返回结果的Thread,请实现 Callable<T> ,其中T代表返回类型.

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";
    }
}

都可以使用 ExecutorService .

Both can be executed using the ExecutorService.

这篇关于将Java线程处理类放到单独的类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆