java – 两个线程可以同时访问对象的2个同步方法吗?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 两个线程可以同时访问对象的2个同步方法吗?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1873字,纯文字阅读大概需要3分钟。
内容图文
![java – 两个线程可以同时访问对象的2个同步方法吗?](/upload/InfoBanner/zyjiaocheng/796/dabe9f0a84b8466ea356427d7885ebc0.jpg)
我在接受采访时问了这个问题.在我告诉他之前,
Once a thread enters any synchronized method on an instance, no other
thread can enter any other synchronized method on the same instance.
考虑一下片段:
Q1:
public class Q1 {
int n;
boolean valueSet = false;
synchronized int get() {
while (!valueSet)
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n) {
while (valueSet)
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}
Producer1:
public class Producer1 implements Runnable {
Q1 q;
Producer1(Q1 q) {
this.q = q;
new Thread(this, "Producer").start();
}
@Override
public void run() {
int i = 0;
while (true) {
q.put(i++);
}
}
}
Consumer1
public class Consumer1 implements Runnable {
Q1 q;
Consumer1(Q1 q) {
this.q = q;
new Thread(this, "Consumer").start();
}
@Override
public void run() {
while (true) {
q.get();
}
}
}
PC1:
public class PC1 {
public static void main(String args[]) {
Q1 q = new Q1();
new Producer1(q);
new Consumer1(q);
System.out.println("Press Control-C to stop.");
}
}
所以,他一旦你创建了这个线程新的Producer1(q),然后根据你的说法,同步的int get()方法必须被同一个线程锁定,即当它被访问时被新的Producer1(q)锁定synchronized int put().我说是.
但我检查了eclipse,get可以被新的Consumer1(q)调用.该计划完美无缺.
我哪里错了?
O / P:
解决方法:
对wait()的调用将释放监视器等待的时间.
这就是Object.wait()的文档:
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.
内容总结
以上是互联网集市为您收集整理的java – 两个线程可以同时访问对象的2个同步方法吗?全部内容,希望文章能够帮你解决java – 两个线程可以同时访问对象的2个同步方法吗?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。