Reputation: 642
I'm trying to wait a thread in a static context until it meets a condition in Java.
As far as I understand, Object.wait()
causes the current thread to wait until another thread notifies the object that it's pending on.
So I tried to apply the same mechanism on a static method, but since the context is static, wait()
will cause the current thread to wait on the class, and notify()
will notify the class itself, not the object.
However, in a static context, the current object is not defined. So how can I even call the wait()
method?
public static synchronized void waitThread() {
//how can I call the current thread to wait in a static method?
//wait();
}
Upvotes: 1
Views: 1666
Reputation: 2395
wait() is an Object method, not a Thread method. I suggest you use a static lock object as in this example:
public class ThreadTest {
Thread1 t1;
Thread2 t2;
static Object lock = new Object();
public static void main(String[] args) {
new ThreadTest().go();
}
private void go() {
t1 = new Thread1();
t2 = new Thread2();
t1.start();
t2.start();
}
private class Thread1 extends Thread {
@Override
public void run() {
ThreadTest.print("ONE");
synchronized (lock) {
lock.notify();
}
}
}
private class Thread2 extends Thread {
@Override
public void run() {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
}
synchronized (lock) {
lock.notify();
}
ThreadTest.print("two");
}
}
private static void print(String str) {
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
}
}
for (int i = 0; i < str.length(); i++) {
System.out.print(str.charAt(i));
try {
Thread.sleep(300);
} catch (InterruptedException e) {
}
}
}
}
Thanks to the wait() and notify() calls, the printouts look good. Without them, the printouts will be mixed up.
Also please consider CountDownLatch which would be a more sophisticated ways to make threads coordinate.
Upvotes: 2