如何在静态上下文中等待线程? [英] How to Wait a Thread in a Static Context?

查看:47
本文介绍了如何在静态上下文中等待线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在静态上下文中等待一个线程,直到它满足 Java 中的条件.

I'm trying to wait a thread in a static context until it meets a condition in Java.

据我所知,Object.wait() 导致当前线程等待,直到另一个线程通知对象它正在挂起.

As far as I understand, Object.wait() causes the current thread to wait until another thread notifies the object that it's pending on.

所以我尝试在静态方法上应用相同的机制,但是由于上下文是静态的,wait() 将导致当前线程在类上等待,并且 notify() 将通知类本身,而不是对象.

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.

然而,在静态上下文中,当前对象并没有被定义.那么我怎样才能调用 wait() 方法呢?

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();
}

推荐答案

wait() 是一个 Object 方法,而不是一个 Thread 方法.我建议您使用静态锁定对象,如本例所示:

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) {
        }
    }
}

}

感谢 wait() 和 notify() 调用,打印输出看起来不错.没有它们,打印输出将被混淆.

Thanks to the wait() and notify() calls, the printouts look good. Without them, the printouts will be mixed up.

另外请考虑 CountDownLatch,它是一种更复杂的线程协调方式.

Also please consider CountDownLatch which would be a more sophisticated ways to make threads coordinate.

这篇关于如何在静态上下文中等待线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆