【问题标题】:How do I perform multithreading in GWT?如何在 GWT 中执行多线程?
【发布时间】:2013-07-28 08:32:47
【问题描述】:

我有一个相当标准的 GWT 表单,它执行从注册表中获取数据并将其存储在数据库中的非常基本的功能。

authenticationService.registerStudent(email, password, firstName, lastName, contact,
            country, countryCode, school, lecturerFirstName, lecturerLastName,
            lecturerEmail, language, new AsyncCallback<Boolean>() {

        @Override
        public void onFailure(Throwable throwable) {

        }

        @Override
        public void onSuccess(Boolean bool) {

        }
    });

在服务器端,我有一个将数据存储到数据库中的 servlet。

public class AuthenticationServiceImpl extends RemoteServiceServlet implements AuthenticationService {

@Override
public Boolean registerStudent(String email, String password, String firstName, String lastName,
                               String contact, String country, String countryCode, String school,
                               String lecturerFirstName, String lecturerLastName, String lecturerEmail,
                               String language) throws IllegalArgumentException {

    ....

    }
}

我想向该人发送一封确认电子邮件,要求他确认帐户。在registerStudent() 函数中实现电子邮件逻辑的问题是与 SMTP 服务器通信可能需要一段时间,这将导致客户端无响应。

如何将发送电子邮件功能“委托”给另一个类/函数,同时在成功插入数据库后能够从registerStudent() 函数返回true?我认为将需要某种形式的多线程,但我不确定如何去做。

【问题讨论】:

  • 我同意 sanbhat 的回答。尽管如此,特别是对于这个关于发送注册电子邮件的问题,我会说同步发送电子邮件(即:锁定客户端并等待发送电子邮件)并不是一个糟糕的选择,因为那时你如果发送电子邮件出现问题,将能够向客户提供反馈,例如“服务超载,请稍后再试”....

标签: java gwt


【解决方案1】:

AuthenticationServiceImpl 是一个 GWT Servlet,这里对任何 Java 库的使用没有没有限制。您可以创建一个Runnable 并将其传递给Thread 并调用start() 以便它并行发送邮件。 runnable的run()方法应该有发送邮件的逻辑。

您可以查看更多关于多线程的文档和示例here

【讨论】:

  • 我认为这是正确的答案,因为重要的是:您可以在 servlet 中做任何您想做的事情。然后,根据您在服务器端使用的框架,可能有数千种可能的实现和设计来发送该电子邮件:)
【解决方案2】:

由于在服务器端您可以完全访问 Java 类库,因此您可以使用线程来启动一个负责发送电子邮件的新线程。

类似这样的:

public class sendRegistrationEmail implements Runnable {
   @Override public void run() {
      ... here goes the code to send email ...
}

然后您可以使用以下方法开始一个新线程:

Thread emailThread = new Thread( new sendRegistrationEmail() );
emailThread.start();

【讨论】:

    猜你喜欢
    • 2011-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多