简体   繁体   English

Java线程同步

[英]Java Thread synchronization

Is there a way for a thread that starts a new thread to wait until the thread it started has stopped? 有没有办法让启动新线程的线程等待直到其启动的线程停止? I was thinking about using locked, but then if the thread crashes, the lock will never get release. 我当时正在考虑使用锁定,但是如果线程崩溃,锁定将永远不会被释放。

so when my program calls 所以当我的程序调用

cTurnCardOvrerConnection thread = new cTurnCardOvrerConnection("thread3", connection, mPlayerList, mPlayersMessages, lBoard);

will it wait until the thread is finished? 它会等到线程完成吗?

mPlayerList.WaitForAllPlayers();
do
{
    do
    {
        r=GetClient();
        switch(r)
        {
            case 0: return; // exitvon a very bad error
        }
    } while(r==2); // loop if it was a timeout wait for this thread to terminate.                   

    cTurnCardOvrerConnection thread = new cTurnCardOvrerConnection("thread3", connection, mPlayerList, mPlayersMessages, lBoard);               
    if ( CheckTimeStamp())
        break;
} while( mPlayerList.AllPlayersFinished()==false);

you can just use Thread.join() . 您可以只使用Thread.join()

of course, if the primary thread is just launching the secondary thread and then waiting for it to finish, there's really no use for the secondary thread (just do the work on the primary thread). 当然,如果主线程只是启动辅助线程,然后等待其完成,则辅助线程实际上没有任何用处(只需在主线程上进行工作即可)。

尝试使用CountDownLatch

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM