Execution of new thread inside a synchronized block

为君一笑 提交于 2019-12-19 05:18:59

问题


If i create a new thread inside a synchronized block, will the block remain locked till the thread execution is also complete? If not, then till when would it remain locked?

String sLine;
onClick(String line){
    synchronized (lock) {
        sLine = line;
        new Thread(new Runnable() {
            @Override
            public void run() {
                 doProcessing(Sline);    
        }).start(); 
    }
}

回答1:


It would only remained locked if the code join()d with the newly created thread, thus waiting for it to finish. As there is no join() the lock will be released after the call to start() has completed.




回答2:


no thread has a separate life. synchronized block will be blocked only till starting point of the thread in above case.



来源:https://stackoverflow.com/questions/15926400/execution-of-new-thread-inside-a-synchronized-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!