如何在静态上下文中等待线程?
How to Wait a Thread in a Static Context?
我试图在静态上下文中等待一个线程,直到它满足 Java 中的条件。
据我了解,Object.wait()
导致当前线程等待,直到另一个线程通知对象它正在挂起。
所以我尝试在静态方法上应用相同的机制,但是由于上下文是静态的,wait()
将导致当前线程在 class 上等待,而 notify()
将通知 class 本身,而不是对象。
但是,在静态上下文中,未定义当前对象。那么我怎么才能调用 wait()
方法呢?
public static synchronized void waitThread() {
//how can I call the current thread to wait in a static method?
//wait();
}
wait() 是对象方法,不是线程方法。我建议你像这个例子一样使用静态锁对象:
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,它是使线程协调的更复杂的方法。
我试图在静态上下文中等待一个线程,直到它满足 Java 中的条件。
据我了解,Object.wait()
导致当前线程等待,直到另一个线程通知对象它正在挂起。
所以我尝试在静态方法上应用相同的机制,但是由于上下文是静态的,wait()
将导致当前线程在 class 上等待,而 notify()
将通知 class 本身,而不是对象。
但是,在静态上下文中,未定义当前对象。那么我怎么才能调用 wait()
方法呢?
public static synchronized void waitThread() {
//how can I call the current thread to wait in a static method?
//wait();
}
wait() 是对象方法,不是线程方法。我建议你像这个例子一样使用静态锁对象:
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,它是使线程协调的更复杂的方法。