sleep会使线程放弃锁吗

theoffspring theoffspring 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
When a thread has yielded as a result of yield(), it releases its locks.

When a thread is sleeping as a result of sleep(), it releases its locks.

这两人句话有什么不对?
对于sleep,api说不会放弃监视器,似乎是指锁,但我做了个例子,发现还是会放弃啊。到底怎么回事。

public class Threads4 {
public static void main(String[] args) throws Exception{
class Mythread implements Runnable{
Threads4 t4;
Mythread(Threads4 t4) {
this.t4=t4;
}

public void run() {
System.out.println("start "+Thread.currentThread().getId());
try {
t4.go();
} catch (Exception e) {
e.printStackTrace();
}

System.out.println("end "+Thread.currentThread().getId());
}
}
Threads4 t4=new Threads4();

Thread t1=new Thread(new Mythread(t4));
Thread t2=new Thread(new Mythread(t4));
t1.start();
Thread.sleep(2000);
t2.start();


}

public synchronized void go(){
System.out.println(Thread.currentThread().getId());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}

}
...全文

相关推荐

评论 17
收藏 已收藏
分享
返回顶部
theoffspring
Java SE 62,621 成员 307,251 内容