在Groovy中使用synchronized println和println作为线程脚本有什么区别?
synchronized out(message) {
println(message)
}
def thread1 = Thread.start {
out "TEST"
}
def thread2 = Thread.start {
out "TEST"
}
def thread3 = Thread.start {
out "TEST"
}
答案 0 :(得分:0)
在您调用single println命令之前没有区别。一个println在内部同步。但是如果你的out包含多个打印语句,可能会出现这种情况,如下所示
out(int threadId){
println("line 1 T$threadId")
println("line 2 T$threadId")
}
Execution may flow like
//output by 2 threads
line 1 T1 // thread 1 entered out
// thread 1 was interrupted
// thread 2 entered out
line 1 T2
line 2 T2 //end of thread 2 out
// Thread 1 resumed
line 2 T1
正如我们所见,输出是混乱的。同步修复了这个问题
另见关于println内同步的SO答案 https://stackoverflow.com/a/9459886/1601606