亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《Thread.sleep() 暂停线程时,线程持有的锁是谁?》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

thread.sleep() 引发的疑问
在多线程编程中,使用 thread.sleep() 方法暂停线程时可能会引发疑问,例如:
问题:
在以下代码示例中,thread.sleep(1000*20) 方法被调用。请问此时线程持有的锁是谁?run 对象还是其他对象?
class Run implements Runnable {
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + " begin...");
Thread.sleep(1000 * 20);
System.out.println(Thread.currentThread().getName() + " over...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class TestThread {
public static void main(String[] args) {
Run run = new Run();
new Thread(run).start();
new Thread(run).start();
}
}答案:
在给定的代码中,线程类没有添加任何显式锁。因此,目前不存在所持有的锁的概念。
解释:
thread.sleep() 方法是静态方法,它会暂停调用它的线程的执行。在这种情况下,run 方法没有synchronized关键字,也没有任何其他类型的锁。因此,thread.sleep() 方法不会获取或释放任何锁。
只有在使用诸如 synchronized 或 reentrantlock 之类的同步机制时,线程才需要获取锁。
到这里,我们也就讲完了《Thread.sleep() 暂停线程时,线程持有的锁是谁?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
本文内容来源于互联网,如有侵权请联系删除。
