我试图在静态上下文中等待线程,直到它满足Java中的条件为止。
据我了解,Object.wait()
导致当前线程等待,直到另一个线程通知对象该对象挂起。
因此,我尝试在静态方法上应用相同的机制,但是由于上下文是静态的,wait()
将导致当前线程在类上等待,而notify()
将通知类本身,而不是对象。
但是,在静态上下文中,当前对象未定义。那么,我怎么甚至可以调用wait()
方法呢?
public static synchronized void waitThread() {
//how can I call the current thread to wait in a static method?
//wait();
}
答案 0 :(得分:1)
wait()是一个Object方法,而不是Thread方法。我建议您在此示例中使用静态锁对象:
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) {
}
}
}
}
由于使用了wait()和notify()调用,因此打印输出看起来不错。没有它们,打印输出将被混淆。
还请考虑CountDownLatch,这将是使线程协调的更复杂的方法。