使用wait()实现线程的有序执行
发布时间:2024-01-02 15:37:52
在Java中,可以使用wait()和notify()方法来实现线程的有序执行。wait()方法使当前线程进入等待状态,直到其他线程调用相同对象的notify()或notifyAll()方法才能继续执行。这样可以实现线程的顺序执行。
下面是一个使用wait()和notify()实现线程有序执行的示例:
public class OrderedThreadExecution {
private int currentThread = 1; // 当前线程
private final Object lock = new Object(); // 用于同步的锁
public static void main(String[] args) {
OrderedThreadExecution orderedExecution = new OrderedThreadExecution();
Thread threadA = new Thread(() -> {
try {
orderedExecution.printNumber(1); // 执行线程 A 的任务
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread threadB = new Thread(() -> {
try {
orderedExecution.printNumber(2); // 执行线程 B 的任务
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread threadC = new Thread(() -> {
try {
orderedExecution.printNumber(3); // 执行线程 C 的任务
} catch (InterruptedException e) {
e.printStackTrace();
}
});
threadA.start();
threadB.start();
threadC.start();
}
public void printNumber(int number) throws InterruptedException {
synchronized (lock) {
while (number != currentThread) {
lock.wait(); // 当前线程不是要执行的线程,进入等待状态
}
System.out.println("Thread " + number + " is executing."); // 打印执行的线程编号
Thread.sleep(1000); // 模拟线程执行的耗时操作
if (currentThread < 3) {
currentThread++; // 切换到下一个线程
} else {
currentThread = 1; // 当前线程为最后一个线程,切换到 个线程
}
lock.notifyAll(); // 唤醒所有等待的线程
}
}
}
在上述示例中,OrderedThreadExecution类表示一个可执行的任务。在main方法中,我们创建了三个线程threadA、threadB和threadC,它们分别代表三个需要顺序执行的任务。
每个线程在运行时,调用printNumber方法来执行自己的任务。在这个方法中,我们使用synchronized关键字来保证线程间的同步,while循环不断检查number和currentThread是否相等,如果不相等,则调用wait()方法进入等待状态。
当当前线程是要执行的线程时,打印当前线程的编号,并模拟一个耗时操作。然后切换到下一个线程,如果当前线程是最后一个线程,则切换到 个线程。最后,调用notifyAll()方法来唤醒所有等待的线程,使它们可以继续执行。
通过上述方式,我们可以实现线程的有序执行:先执行线程A的任务,再执行线程B的任务,最后执行线程C的任务。
