Java让线程等待
在多线程编程中,有时候我们需要让一个线程等待另一个线程的完成,再继续执行下面的代码。Java提供了一些机制来实现线程的等待,本文将介绍几种常见的方法,并提供示例代码来说明它们的用法。
1. 使用Thread的join()方法
Thread类提供了join()方法,它可以让当前线程等待调用join()方法的线程完成后再继续执行。下面是一个简单的示例代码:
public class ThreadJoinExample {
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println("Thread 1: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread2 = new Thread(() -> {
try {
thread1.join(); // 等待thread1完成
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 5; i++) {
System.out.println("Thread 2: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread1.start();
thread2.start();
}
}
在上面的代码中,我们创建了两个线程thread1和thread2。在thread2中,我们使用thread1.join()方法让thread2等待thread1完成后再继续执行。运行上述代码,你将看到thread2在thread1执行完毕后才开始执行。
2. 使用Object的wait()和notify()方法
除了使用Thread类的join()方法,我们还可以使用Object的wait()和notify()方法来实现线程的等待和唤醒。wait()方法会让当前线程进入等待状态,直到其他线程调用对象的notify()方法来唤醒它。下面是一个示例代码:
public class ThreadWaitNotifyExample {
public static void main(String[] args) {
Object lock = new Object();
Thread thread1 = new Thread(() -> {
synchronized (lock) {
try {
lock.wait(); // 等待唤醒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Thread 1: Hello from thread 1!");
});
Thread thread2 = new Thread(() -> {
synchronized (lock) {
System.out.println("Thread 2: Hello from thread 2!");
lock.notify(); // 唤醒等待的线程
}
});
thread1.start();
thread2.start();
}
}
在上述代码中,我们创建了两个线程thread1和thread2。在thread1中,我们使用lock.wait()方法让线程进入等待状态。在thread2中,我们使用lock.notify()方法唤醒等待的线程。当thread1被唤醒后,它将继续执行并打印一条消息。
3. 使用CountDownLatch类
CountDownLatch是Java提供的一个同步辅助类,它可以让一个或多个线程等待其他线程完成后再继续执行。下面是一个示例代码:
import java.util.concurrent.CountDownLatch;
public class ThreadCountDownLatchExample {
public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(1);
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println("Thread 1: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
latch.countDown(); // 计数减一
});
Thread thread2 = new Thread(() -> {
try {
latch.await(); // 等待计数变为0
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 5; i++) {
System.out.println("Thread 2: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread1.start();
thread2.start();
}
}
在上述代码中,我们创建了一个CountDownLatch对象,并将计数器初始化为1。在thread1中,计数器减一后