Java多线程与并发 --- notify 和 notifyall 的区别

 notify 和 notifyall  唤醒锁

notify 和 notifyall  的区别

先明白两个概念:

锁池:EntryList

等待池:WaitSet

 这个时候 再来看 notify 和 notifyall  的区别:

notifyall : 会让所有处于等待池的线程全部进入锁池去竞争获取锁的机会

notify : 只会随机选取一个处于等待池中的线程进入锁池中去竞争获取锁的机会

  1. public class NotificationDemo {
  2. private volatile boolean go = false;
  3.  
  4. public static void main(String args[]) throws InterruptedException {
  5. final NotificationDemo test = new NotificationDemo();
  6.  
  7. Runnable waitTask = new Runnable(){
  8.  
  9. @Override
  10. public void run(){
  11. try {
  12. test.shouldGo();
  13. } catch (InterruptedException e) {
  14. e.printStackTrace();
  15. }
  16. System.out.println(Thread.currentThread().getName() + " finished Execution");
  17. }
  18. };
  19.  
  20. Runnable notifyTask = new Runnable(){
  21.  
  22. @Override
  23. public void run(){
  24. test.go();
  25. System.out.println(Thread.currentThread().getName() + " finished Execution");
  26. }
  27. };
  28.  
  29. Thread t1 = new Thread(waitTask, "WT1"); //will wait
  30. Thread t2 = new Thread(waitTask, "WT2"); //will wait
  31. Thread t3 = new Thread(waitTask, "WT3"); //will wait
  32. Thread t4 = new Thread(notifyTask,"NT1"); //will notify
  33.  
  34. //starting all waiting thread
  35. t1.start();
  36. t2.start();
  37. t3.start();
  38.  
  39. //pause to ensure all waiting thread started successfully
  40. Thread.sleep(200);
  41.  
  42. //starting notifying thread
  43. t4.start();
  44.  
  45. }
  46. /*
  47. * wait and notify can only be called from synchronized method or bock
  48. */
  49. private synchronized void shouldGo() throws InterruptedException {
  50. while(go != true){
  51. System.out.println(Thread.currentThread()
  52. + " is going to wait on this object");
  53. wait(); //release lock and reacquires on wakeup
  54. System.out.println(Thread.currentThread() + " is woken up");
  55. }
  56. go = false; //resetting condition
  57. }
  58.  
  59. /*
  60. * both shouldGo() and go() are locked on current object referenced by "this" keyword
  61. */
  62. private synchronized void go() {
  63. while (go == false){
  64. System.out.println(Thread.currentThread()
  65. + " is going to notify all or one thread waiting on this object");
  66.  
  67. go = true; //making condition true for waiting thread
  68. //notify(); // only one out of three waiting thread WT1, WT2,WT3 will woke up
  69. notifyAll(); // all waiting thread WT1, WT2,WT3 will woke up
  70. }
  71.  
  72. }
  73. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值