Since your program is a GUI program (I'm gathering by the repaint()
call), it is inherently multi-threaded, even if you don't know it. (If not, it will behave very badly.)
If you are not using Threads, then you cannot use wait/notify or any other kind of synchronization, since there aren't two threads to synchronize. But you don't have to explicitly use Threads, necessarily, in a GUI program to end up using Threads.
Note that the Java compiler won't warn you if you use methods relying on Threads but don't actually use Threads in any way.
You have one of the following problems:
1) You are using Threads without knowing about it and you are using two different monitor objects. Thus, when you call notify()
, it is notifying the monitor for that object, but not for the first object where you are calling wait()
. There are many possible solutions. One of the easiest is to use the JDK 5 concurrency utilities to do this, which are MUCH nicer than the built-in base monitor wait/notify methods. Or,
2) You are running in a single Thread and the wait/notify does not good. It just doesn't make sense in a single-Threaded program to wait for another Thread to notify -- there's no other thread that can do so.
Assuming that you are actually using more than one Thread, a good way to solve this with Java 5 and later is with a semaphore, perhaps by, in the class containing mark()
and simplifying a bit:
private final Semaphore sem = new Semaphore(1);
public void mark(int var) {
sem.acquire();
//change some stuff
repaint();
sem.release();
}
waitForSemaphore() {
sem.acquire();
}
and then in compute
, call waitForSemaphore()
when you want to wait to be notified by mark()
. Because mark()
already acquired the semaphore, you'll have to wait for mark()
to release the semaphore before compute will be able to get it by calling waitForSemaphore()
.