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

07-24 09:45
查看更多