简体   繁体   中英

Using synchronization locks in Java

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?

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.

Alternatively you could change one of them to do their work first, then call notify() , then wait() . Again, you'd have to be sure the other thread was already waiting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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