在Java中使用同步锁
我一直在搞乱 Java 中的同步,但它对我来说还没有工作。
我有两个 Runnable 对象,用于创建单独的线程,每个对象都有一个共享 ArrayList 和一个共享对象的句柄(用于同步)。第一个 Runnable 始终读取数组列表中所有对象的某个实例变量,第二个 Runnable 不断更新数组列表中所有对象的实例变量。
按照我现在设置的方式,两个 Runnable 对象都包含一个指向我打算用作锁的对象的指针。
Runnable 1:
public void run() {
if (syncLock == null)
return;
synchronized (syncLock) {
try {
syncLock.wait();
} catch (InterruptedException e) {
}
for (int i = 0; i < list.size(); i++) {
drawItem(list.get(i));
}
syncLock.notify();
}
}
Runnable 2:
public void run() {
if (syncLock == null)
return;
synchronized (syncLock) {
try {
syncLock.wait();
} catch (InterruptedException e) {
}
for (int i = 0; i < list.size(); i++) {
updateItem(list.get(i));
}
syncLock.notify();
}
}
因此从技术上讲,第一个 Runnable 始终在屏幕上绘制对象,第二个 Runnable 则根据时间变化计算项目的新位置。
我缺少什么吗?
I have been messing around with synchronization in Java and it has yet to work for me.
I have two Runnable objects that are used to create separate threads, and each object has a handle to a shared ArrayList and a shared Object (for use in synchronized). The first Runnable is always reading tsome instance variable for all of the Objects in the array list, and the second Runnable continuously updates the instance variables for all of the Objects in the array list.
The way I have it setup now, both Runnable objects contain a pointer to an Object that I intended to function as a lock.
Runnable 1:
public void run() {
if (syncLock == null)
return;
synchronized (syncLock) {
try {
syncLock.wait();
} catch (InterruptedException e) {
}
for (int i = 0; i < list.size(); i++) {
drawItem(list.get(i));
}
syncLock.notify();
}
}
Runnable 2:
public void run() {
if (syncLock == null)
return;
synchronized (syncLock) {
try {
syncLock.wait();
} catch (InterruptedException e) {
}
for (int i = 0; i < list.size(); i++) {
updateItem(list.get(i));
}
syncLock.notify();
}
}
So technically the first Runnable is always drawing the objects on-screen and the second is calculating the items' new position based on change in time.
Anything I am missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来您的两个线程都将启动并陷入
wait()
中,除非您还有其他一些对象没有显示给其中一个notify()
它们(只是为了启动它们。)您必须确保两个线程都在等待。或者,您可以将其中一个更改为首先执行其工作,然后调用
notify()
,然后调用wait()
。同样,您必须确保另一个线程已经在等待。It looks like both your threads are going to start and get stuck in
wait()
, unless you have some other object you aren't showing there tonotify()
one of them (just to start them off.) You'd have to be sure that both threads were waiting.Alternatively you could change one of them to do their work first, then call
notify()
, thenwait()
. Again, you'd have to be sure the other thread was already waiting.