首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Groovy多线程意外停止

Groovy多线程意外停止
EN

Stack Overflow用户
提问于 2017-12-22 02:15:17
回答 1查看 128关注 0票数 0

我还为结果保留了一个由信号量组成的互斥锁,并且这个条件被很好地保留了下来,直到脚本返回null并且没有到达最终的print。

代码语言:javascript
复制
    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"
EN

回答 1

Stack Overflow用户

发布于 2018-01-03 23:02:58

以下简化的代码可以很好地工作:

代码语言:javascript
复制
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"

结果:

代码语言:javascript
复制
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

即使你在任何线程中都会有异常,这段代码也会到最后。

因此,多线程工作得很好,问题出在代码的其余部分。

提供可运行的代码,这样我们就可以看到问题...

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47930554

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档