我试图在静态上下文中等待线程,直到它满足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();
}
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,这将是使线程协调的更复杂的方法。