luc*_*cas 4 concurrency groovy
我正在尝试在Groovy中编写一个可重用的组件,以便轻松地从我们的一些Java应用程序中发送电子邮件.我想传递一个List,其中Email只是一个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() }
}
Run Code Online (Sandbox Code Playgroud)
我希望睡眠会随机减慢一些线程,因此控制台输出不会是连续的.相反,我看到了这个:
putting thread in list
putting thread in list
putting thread in list
putting thread in list
putting thread in list
putting thread in list
putting thread in list
putting thread in list
putting thread in list
putting thread in list
in closure
sending email1
in closure
sending email2
in closure
sending email3
in closure
sending email4
in closure
sending email5
in closure
sending email6
in closure
sending email7
in closure
sending email8
in closure
sending email9
in closure
sending email10
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
Chr*_*orf 12
为了让您在上面同时运行示例,您必须替换该行
threads.each { it.run() }
Run Code Online (Sandbox Code Playgroud)
同
threads.each { it.start() }
Run Code Online (Sandbox Code Playgroud)
因为run()没有启动新线程,因此您的代码按顺序运行.
还有一个名为GPars的Groovy扩展.它支持几种并发技术,如Fork/Join或Actor模型.使用GPars,您的代码可以简化为:
def sendEmails(emails) {
GParsPool.withPool {
emails.eachParallel { email ->
def wait = (long) new Random().nextDouble() * 1000
println "in closure"
this.sleep wait
sendEmail(email)
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15004 次 |
| 最近记录: |