简体   繁体   English

在Java中使用同步锁

[英]Using synchronization locks in Java

I have been messing around with synchronization in Java and it has yet to work for me. 我一直在搞弄Java同步,但它尚未为我工作。

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). 我有两个用于创建单独线程的Runnable对象,每个对象都有一个共享ArrayList和共享对象(用于同步)的句柄。 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. 第一个Runnable始终读取数组列表中所有对象的tsome实例变量,第二个Runnable连续更新数组列表中所有对象的实例变量。

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对象都包含一个指向我打算用作锁的对象的指针。

Runnable 1: 可运行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: 可运行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. 因此,从技术上讲,第一个Runnable总是在屏幕上绘制对象,第二个基于时间的变化来计算项目的新位置。

Anything I am missing? 我有什么想念的吗?

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 to notify() one of them (just to start them off.) You'd have to be sure that both threads were waiting. 看起来您的两个线程都将启动并陷入wait() ,除非您有其他对象,否则您不会在其中显示notify()之一(只是将它们启动)。确保两个线程都在等待。

Alternatively you could change one of them to do their work first, then call notify() , then wait() . 或者,您可以更改其中一个先执行其工作,然后调用notify() ,然后调用wait() Again, you'd have to be sure the other thread was already waiting. 同样,您必须确保另一个线程已经在等待。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM