有关thread的两个实例获得锁的问题
来源:7-2 wait方法

佛系biu
2020-03-08
package threadcoreknowledge.threadobjectclasscommonmethods;
/** 展示wait和notify的基本用法
* 1.研究代码的执行顺序
* 2.证明wait释放锁
* @author Just Happy
*/
public class Wait {
public static Object object = new Object();
static class Thread1 extends Thread{
@Override
public void run() {
synchronized (object){
System.out.println("线程"+Thread.currentThread().getName()+"开始执行了");
try {
//释放锁
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程"+Thread.currentThread().getName()+"获得了锁");
}
}
}
static class Thread2 extends Thread{
@Override
public void run() {
synchronized (object){
// notify不会立刻释放锁,会把代码块执行完
object.notify();
System.out.println("线程"+Thread.currentThread().getName()+"调用了notify()");
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread1 thread1 = new Thread1();
Thread1 thread2 = new Thread1();
Thread2 thread3 = new Thread2();
thread1.start();
Thread.sleep(300);
thread2.start();
Thread.sleep(300);
thread3.start();
}
}
实验结果:
我的理解是Thread1的两个实例只有一个会获得锁,但是为什么好像一开始都打印出那句话了,synchronzied关键字的范围怎么变小了啊?
写回答
2回答
-
我的理解是Thread1的两个实例只有一个会获得锁,但是为什么好像一开始都打印出那句话了
因为你调用了object.wait()释放了锁,所以第二个线程就拿到锁了,你在wait之前加睡眠5秒就能明显看出来了。
Object.nofity() 的文档明确说一个随机的线程将被唤醒:
If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation.
但具体情况将由实现者决定,因为Object.nofity()是一个native方法。
032020-03-09 -
佛系biu
提问者
2020-03-08
还有一个问题,为什么每次都是先执行wait的方法先被唤醒,notify不是随机的吗?
00
相似问题
synchonized的问题
回答 1
老师,关于锁和处理器资源的问题
回答 1