Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Concurrency 如何并行化这个groovy代码?_Concurrency_Groovy - Fatal编程技术网

Concurrency 如何并行化这个groovy代码?

Concurrency 如何并行化这个groovy代码?,concurrency,groovy,Concurrency,Groovy,我正在尝试用Groovy编写一个可重用组件,以便轻松地发送来自一些Java应用程序的电子邮件。我想给它一个列表,其中的电子邮件只是一个POJO(POGO?)和一些电子邮件信息。我希望它是多线程的,至少在第二个线程中运行所有电子邮件逻辑,或者每个电子邮件一个线程 我对Java中的多线程非常迷茫,所以这可能没有帮助!我尝试了几种不同的方法,但我现在有: void sendEmails(List<Email> emails) { def threads = [] def

我正在尝试用Groovy编写一个可重用组件,以便轻松地发送来自一些Java应用程序的电子邮件。我想给它一个列表,其中的电子邮件只是一个POJO(POGO?)和一些电子邮件信息。我希望它是多线程的,至少在第二个线程中运行所有电子邮件逻辑,或者每个电子邮件一个线程

我对Java中的多线程非常迷茫,所以这可能没有帮助!我尝试了几种不同的方法,但我现在有:

void sendEmails(List<Email> emails) {

    def threads = []

    def sendEm = emails.each{ email ->
        def th = new Thread({
            Random rand = new Random()
            def wait = (long)(rand.nextDouble() * 1000)
            println "in closure"
            this.sleep wait
            sendEmail(email)
        })
        println "putting thread in list"
        threads << th
    }

    threads.each { it.run() }
    threads.each { it.join() }

}
sendEmail基本上实现了您期望的功能,包括println语句,调用它的客户端如下所示

void doSomething() {

    Mailman emailer = MailmanFactory.getExchangeEmailer()

    def to = ["one","two"]
    def from = "noreply"

    def li = []
    def email   
    (1..10).each {
        email = new Email(to,null,from,"email"+it,"hello")
        li << email
    }

    emailer.sendEmails li
}
void doSomething(){
Mailman emailer=MailmanFactory.getExchangeEmailer()
def to=[“一”、“二”]
def from=“noreply”
def li=[]
def电子邮件
(1..10)每个{
电子邮件=新电子邮件(收件人,空,发件人,“电子邮件”+它,“你好”)

li一些Java版本(1.5)推出了一些新的并发功能,使Java线程(甚至更)简单。Google for Java ThreadExecutor,您会发现一些页面,如:


我不能说Groovy是否会让它变得更简单,但在进行比较之前,您可能希望首先将“新”Java技术应用到您的Java示例中。

要使上述示例同时运行,您必须替换该行

threads.each { it.run() }

由于
run()
不会启动新线程,因此代码是按顺序运行的

还有一个Groovy扩展名为。它支持多种并发技术,如Fork/Join或Actor模型。使用GPAR,您的代码可以简化为:

def sendEmails(emails) {

  GParsPool.withPool {
    emails.eachParallel { email ->
      def wait = (long) new Random().nextDouble() * 1000 
      println "in closure"
      this.sleep wait
      sendEmail(email)
    }
  }

}

谢谢Don,这很有帮助。我用threadExecutor.execute替换了运行和加入,然后是threadExecutor.shutdown(),最后是threadExecutor.awaitTermination(1,TimeUnit.MINUTES),因为我认为它过早退出并杀死生成的线程。看起来我现在已经退出并运行了。
threads.each { it.start() }
def sendEmails(emails) {

  GParsPool.withPool {
    emails.eachParallel { email ->
      def wait = (long) new Random().nextDouble() * 1000 
      println "in closure"
      this.sleep wait
      sendEmail(email)
    }
  }

}