java中方法的同步 [英] Synchronization of methods in java

查看:72
本文介绍了java中方法的同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解完全参考中给出的代码。 of Java

展开 | 选择 | Wrap | < span class =codeLinkonclick =LineNumbers(this);>行号

解决方案

@Time
notify() - 唤醒正在等待此对象监视器的单个线程 - 并且等待( ) - 使当前线程等到另一个线程调用此对象的notify()方法或notifyAll()方法 - Object 的方法不是Thread。


@Time


put()从运行中调用(你所说的生产者的方法。


现在在put()中只有在(和while) val 为真时才会发生等待。如果 val 为false,则put()方法继续并打印控制台消息。


也许我错过了你的困惑。


完全..当val的值为true时put将起作用但是当我们第一次调用它时它的值为false ...因为它在book类中设置为false ..

但是输出put方法首先工作;即,它首先显示值,并且get ...接受同一个值后显示值...

但是根据代码,put不是首先执行的那个..

Am having difficulty in understanding how code given in Complete ref. of Java

Expand|Select|Wrap|Line Numbers

解决方案

@Time
notify() - "Wakes up a single thread that is waiting on this object''s monitor" - and wait() - "Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object" - are methods of Object not Thread.


@Time
put() gets called from the run() method of the producer as you say.

Now in put() the waiting only happens when (and while) val is true. If val is false the put() method goes on and prints the console message.

Perhaps I am missing what you are confused about.


exactly.. put will work when value of val is true but when we call it for the first time its value is false... as its set to false in book class..
But in output put method works first; i.e. it displays the value first and same one is accepted by get.. after put has done with displaying value..
but according to the code, put is not the one which will execute first..


这篇关于java中方法的同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆