永发信息网

java 被唤醒的线程能重新得到锁么

答案:2  悬赏:40  手机版
解决时间 2021-12-26 14:23
  • 提问者网友:练爱
  • 2021-12-25 18:43
一个线程在获得锁后,遇到wait(),释放锁,
在另一个线程中唤醒原线程,原线程执行的时候还会得到之前的锁么

------------------------------------------------------------------------------------
我自己又验证了一下,被唤醒的线程会重新得到锁,
若多个线程被同时唤醒,同一个锁的多个线程,只有一个线程得到锁,
其他线程依旧等待得到锁的线程释放该锁,然后其他线程中的一个得到锁,依次处理
最佳答案
  • 五星知识达人网友:逃夭
  • 2021-12-25 19:16
一个被wait后,即使它被notify,它后面的大段代码是继续执行啊。
你这个程序是通过bShouldSub来控制两个方法被交互执行的。
wait就是当前线程被阻塞,直到被另一个线程notify(唤醒),然后当前进程继续执行上次未完成的操作。
下面是API里面写的:
The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.
全部回答
  • 1楼网友:渡鹤影
  • 2021-12-25 20:50
首先,从你程序的本意来看, 你是想用线程实现一个生产者-- 消费者模式, 用在馒头的场景, 如下: 1、 肯定需要一个篮子, 负责装馒头,并且这个篮子有容量,假设容量为c; 2、 有两个人,第一个是爹(生产者), 第二个是娃(消费者), 爹负责向篮子中放入馒头, 娃负责从篮子中取出馒头喂狗; 3、 但是篮子的容量是有限的, 当篮子被装满时, 爹就等待娃从篮子中取出馒头,篮子腾出空间之后,爹继续装馒头; 当篮子的馒头都被取走后, 娃就等待, 当篮子中又被放入馒头时,才继续取馒头。 附上代码: 篮子: public class bucket { private int count = 0; // 篮子能够容纳的馒头数 private int total = 0; // 放馒头的总数 public synchronized void put(){ if(count == 5){ try { system.out.println("俺是他爹,篮子满了,俺在等俺家娃拿馒头喂狗"); wait(); } catch (interruptedexception e) { e.printstacktrace(); } } count += 1; total++; system.out.println("俺是他爹,俺放了一个馒头,现有篮子里有 [" + count + "] 个馒头"); notify(); } public synchronized boolean get(){ if(count == 0){ try { wait(); system.out.println("俺是他娃,篮子空了,俺在等俺爹放馒头到篮子里"); } catch (interruptedexception e) { e.printstacktrace(); } } count -= 1; system.out.println("俺拿了一个馒头喂俺家大花狗, 篮子里还有 [" + count + "] 个馒头"); notify(); if(total == 100 && count == 0){ return false; }else{ return true; } } 爹: public class product implements runnable{ private bucket bucket; product(bucket bucket){ this.bucket = bucket; } @override public void run() { for(int i=0; i<100; i++){ bucket.put(); } system.out.println("俺把馒头都放完了"); } } 娃: public class consumer implements runnable{ private bucket bucket; public consumer(bucket bucket){ this.bucket = bucket; } @override public void run() { while(true){ if(!bucket.get()){ break; } } system.out.println("俺家大花狗吃完馒头了"); } } 启动类: public class test { public static void main(string[] args) { bucket bucket = new bucket(); new thread(new consumer(bucket)).start(); new thread(new product(bucket)).start(); } } 最后附上你的问题, notify 由谁来唤醒: 注意 wait() 和 notify() 是object类上的方法, notify() 的意思是: 从加锁的对象的监视器(监视器就是锁)的等待队列中, 任意取出一个等待线程, 让该线程处于runnable状态; wait()的意思是: 把锁住对象的当前线程, 放入到监视器的等待队列中。 所以,notify()的意思就是要唤醒等待队列中的一个等待线程,当程序发起这么一个事件后, 是由虚拟机的线程调度器完成线程状态之间的转换的。
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯