我还为结果保留了一个由信号量组成的互斥锁,并且这个条件被很好地保留了下来,直到脚本返回null并且没有到达最终的print。
def pathFinder(){
def permutation = []
for (int i = 1; i <= noOfNodes; i++)
permutation.push(i)
while(true){
if( mutex.tryAcquire(MAX_TIME,TimeUnit.MILLISECONDS) )
{ println "mutex acquired"
if(finalFound){
//check if another thread solved the problem
mutex.release()
println "mutex released - solution found"
break
}
println "solution not found"
//release the lock while checking the permutation
mutex.release()
println "mutex released for others to start looking"
permutation = permutation.sort { new Random().nextInt() }
println "permutation generated: "+permutation
if(isPathHamiltonian(permutation)){
if(mutex.tryAcquire(MAX_TIME,TimeUnit.MILLISECONDS))
{
println "mutex acquired for result"
finalPermutation = permutation
finalFound = true
mutex.release()
println "mutex for result released"
break}
}
}
}
}
def threads = []
noOfThreads.times(){
def thread = Thread.start {
pathFinder()
}
threads << thread
}
println "I start waiting"
threads*.join(MAX_TIME)
println "I joined the finished"
if(finalFound == true) println "Graph is proven to be hamiltonian : " + finalPermutation
else println "Graph was not found hamiltonian"发布于 2018-01-03 23:02:58
以下简化的代码可以很好地工作:
def noOfThreads = 3
def MAX_TIME = 30000
def threads = []
def pathFinder(id){
def t=System.currentTimeMillis()
println "thread $id start"
Thread.sleep(3000+id*100)
println "thread $id end: ${(System.currentTimeMillis() - t)/1000} sec"
}
println "START"
noOfThreads.times{id->
def thread = Thread.start {
pathFinder(id)
}
threads << thread
}
threads*.join(MAX_TIME)
println "END"结果:
START
thread 0 start
thread 1 start
thread 2 start
thread 0 end: 3.002 sec
thread 1 end: 3.1 sec
thread 2 end: 3.2 sec
END即使你在任何线程中都会有异常,这段代码也会到最后。
因此,多线程工作得很好,问题出在代码的其余部分。
提供可运行的代码,这样我们就可以看到问题...
https://stackoverflow.com/questions/47930554
复制相似问题