Interview AiBoxInterview AiBox 实时 AI 助手,让你自信应答每一场面试
如何确保三个线程按照指定顺序执行任务?
题型摘要
确保三个线程按指定顺序执行任务有多种方法:1)使用Thread.join()方法使当前线程等待其他线程完成;2)使用单线程ExecutorService按顺序提交任务;3)使用CountDownLatch控制线程启动;4)使用CyclicBarrier让线程互相等待;5)使用Semaphore控制线程访问;6)使用wait/notify机制实现线程通信;7)使用Lock和Condition实现精确同步控制。选择方法应根据具体场景和需求,简单场景可用join()或单线程执行器,复杂场景可选用其他同步机制。
如何确保三个线程按照指定顺序执行任务?
在多线程编程中,确保线程按照指定顺序执行是一个常见的需求。以下是几种确保三个线程按照指定顺序执行任务的方法:
1. 使用Thread.join()方法
join()方法使当前线程等待调用join()方法的线程执行完毕后再继续执行。
public class ThreadJoinExample {
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(() -> {
System.out.println("Thread 1 executed");
}, "Thread-1");
Thread thread2 = new Thread(() -> {
System.out.println("Thread 2 executed");
}, "Thread-2");
Thread thread3 = new Thread(() -> {
System.out.println("Thread 3 executed");
}, "Thread-3");
// 启动线程1
thread1.start();
// 等待线程1完成
thread1.join();
// 启动线程2
thread2.start();
// 等待线程2完成
thread2.join();
// 启动线程3
thread3.start();
// 等待线程3完成
thread3.join();
}
}
2. 使用单个ExecutorService按顺序提交任务
使用单线程的ExecutorService,它会按照任务提交的顺序依次执行任务。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SingleExecutorExample {
public static void main(String[] args) {
// 创建单线程执行器
ExecutorService executor = Executors.newSingleThreadExecutor();
// 按顺序提交任务
executor.submit(() -> {
System.out.println("Thread 1 executed");
});
executor.submit(() -> {
System.out.println("Thread 2 executed");
});
executor.submit(() -> {
System.out.println("Thread 3 executed");
});
// 关闭执行器
executor.shutdown();
}
}
3. 使用CountDownLatch
CountDownLatch是一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException {
// 创建两个CountDownLatch,分别用于控制线程2和线程3的启动
CountDownLatch latch1 = new CountDownLatch(1);
CountDownLatch latch2 = new CountDownLatch(1);
Thread thread1 = new Thread(() -> {
System.out.println("Thread 1 executed");
// 线程1完成后,减少latch1的计数,允许线程2执行
latch1.countDown();
}, "Thread-1");
Thread thread2 = new Thread(() -> {
try {
// 等待latch1的计数变为0
latch1.await();
System.out.println("Thread 2 executed");
// 线程2完成后,减少latch2的计数,允许线程3执行
latch2.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "Thread-2");
Thread thread3 = new Thread(() -> {
try {
// 等待latch2的计数变为0
latch2.await();
System.out.println("Thread 3 executed");
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "Thread-3");
// 启动所有线程
thread1.start();
thread2.start();
thread3.start();
// 等待所有线程完成
thread1.join();
thread2.join();
thread3.join();
}
}
4. 使用CyclicBarrier
CyclicBarrier是一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点。
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierExample {
public static void main(String[] args) {
// 创建两个CyclicBarrier,分别用于控制线程2和线程3的启动
CyclicBarrier barrier1 = new CyclicBarrier(2);
CyclicBarrier barrier2 = new CyclicBarrier(2);
Thread thread1 = new Thread(() -> {
System.out.println("Thread 1 executed");
try {
// 等待线程2到达屏障点
barrier1.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}, "Thread-1");
Thread thread2 = new Thread(() -> {
try {
// 等待线程1到达屏障点
barrier1.await();
System.out.println("Thread 2 executed");
// 等待线程3到达屏障点
barrier2.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}, "Thread-2");
Thread thread3 = new Thread(() -> {
try {
// 等待线程2到达屏障点
barrier2.await();
System.out.println("Thread 3 executed");
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}, "Thread-3");
// 启动所有线程
thread1.start();
thread2.start();
thread3.start();
}
}
5. 使用Semaphore
Semaphore是一个计数信号量,用于控制同时访问特定资源的线程数量。
import java.util.concurrent.Semaphore;
public class SemaphoreExample {
public static void main(String[] args) {
// 创建两个Semaphore,初始许可数为0,分别用于控制线程2和线程3的启动
Semaphore semaphore1 = new Semaphore(0);
Semaphore semaphore2 = new Semaphore(0);
Thread thread1 = new Thread(() -> {
System.out.println("Thread 1 executed");
// 释放一个许可,允许线程2执行
semaphore1.release();
}, "Thread-1");
Thread thread2 = new Thread(() -> {
try {
// 获取一个许可,如果许可数为0则阻塞
semaphore1.acquire();
System.out.println("Thread 2 executed");
// 释放一个许可,允许线程3执行
semaphore2.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "Thread-2");
Thread thread3 = new Thread(() -> {
try {
// 获取一个许可,如果许可数为0则阻塞
semaphore2.acquire();
System.out.println("Thread 3 executed");
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "Thread-3");
// 启动所有线程
thread1.start();
thread2.start();
thread3.start();
}
}
6. 使用wait/notify机制
使用Object类的wait()和notify()/notifyAll()方法可以实现线程间的通信和同步。
public class WaitNotifyExample {
private static final Object lock = new Object();
private static int currentThread = 1;
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
synchronized (lock) {
while (currentThread != 1) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Thread 1 executed");
currentThread = 2;
lock.notifyAll();
}
}, "Thread-1");
Thread thread2 = new Thread(() -> {
synchronized (lock) {
while (currentThread != 2) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Thread 2 executed");
currentThread = 3;
lock.notifyAll();
}
}, "Thread-2");
Thread thread3 = new Thread(() -> {
synchronized (lock) {
while (currentThread != 3) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Thread 3 executed");
lock.notifyAll();
}
}, "Thread-3");
// 启动所有线程
thread1.start();
thread2.start();
thread3.start();
}
}
7. 使用Lock和Condition
使用ReentrantLock和Condition可以实现更灵活的线程同步控制。
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockConditionExample {
private static final Lock lock = new ReentrantLock();
private static final Condition condition1 = lock.newCondition();
private static final Condition condition2 = lock.newCondition();
private static int currentThread = 1;
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
lock.lock();
try {
while (currentThread != 1) {
condition1.await();
}
System.out.println("Thread 1 executed");
currentThread = 2;
condition2.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}, "Thread-1");
Thread thread2 = new Thread(() -> {
lock.lock();
try {
while (currentThread != 2) {
condition2.await();
}
System.out.println("Thread 2 executed");
currentThread = 3;
condition1.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}, "Thread-2");
Thread thread3 = new Thread(() -> {
lock.lock();
try {
while (currentThread != 3) {
condition1.await();
}
System.out.println("Thread 3 executed");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}, "Thread-3");
// 启动所有线程
thread1.start();
thread2.start();
thread3.start();
}
}
方法对比
| 方法 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|
| Thread.join() | 简单直观,易于理解 | 阻塞主线程,不够灵活 | 简单的顺序执行场景 |
| 单线程ExecutorService | 代码简洁,自动管理线程 | 只能在一个线程中执行任务 | 任务需要按顺序执行,且不需要并行处理 |
| CountDownLatch | 灵活,可以控制多个线程的启动 | 需要创建多个CountDownLatch对象 | 需要等待一个或多个线程完成后再执行其他线程 |
| CyclicBarrier | 可重用,适合循环等待 | 需要创建多个CyclicBarrier对象 | 多个线程需要互相等待到达某个屏障点 |
| Semaphore | 可以控制同时访问资源的线程数量 | 需要正确管理许可的获取和释放 | 需要控制同时访问特定资源的线程数量 |
| wait/notify | 基础机制,不依赖额外类 | 实现复杂,容易出错 | 需要线程间通信和同步的场景 |
| Lock和Condition | 灵活,可以实现复杂的同步逻辑 | 代码复杂,需要正确管理锁的获取和释放 | 需要精确控制线程同步和通信的复杂场景 |
执行流程图
下面是使用CountDownLatch确保三个线程按顺序执行的流程图:
总结
确保三个线程按照指定顺序执行任务有多种方法,每种方法都有其适用场景和优缺点。在实际开发中,应根据具体需求选择合适的方法。对于简单的顺序执行场景,可以使用Thread.join()或单线程ExecutorService;对于需要更灵活控制的场景,可以考虑使用CountDownLatch、CyclicBarrier、Semaphore、wait/notify或Lock和Condition等机制。
思维导图
Interview AiBoxInterview AiBox — 面试搭档
不只是准备,更是实时陪练
Interview AiBox 在面试过程中提供实时屏幕提示、AI 模拟面试和智能复盘,让你每一次回答都更有信心。
AI 助读
一键发送到常用 AI
确保三个线程按指定顺序执行任务有多种方法:1)使用Thread.join()方法使当前线程等待其他线程完成;2)使用单线程ExecutorService按顺序提交任务;3)使用CountDownLatch控制线程启动;4)使用CyclicBarrier让线程互相等待;5)使用Semaphore控制线程访问;6)使用wait/notify机制实现线程通信;7)使用Lock和Condition实现精确同步控制。选择方法应根据具体场景和需求,简单场景可用join()或单线程执行器,复杂场景可选用其他同步机制。
智能总结
深度解读
考点定位
思路启发
相关题目
在软件开发中,如何设计有效的测试用例?
设计有效测试用例需遵循明确性、完整性、独立性等原则,运用等价类划分、边界值分析等黑盒测试技术和语句覆盖、分支覆盖等白盒测试技术。针对单元测试、集成测试、系统测试和验收测试等不同级别,采用相应的设计策略和方法。测试用例应包含完整的文档结构,使用专业工具进行管理,并基于风险分析确定优先级。最佳实践包括测试用例复用、自动化测试和定期评审,避免过度依赖脚本、忽视负面测试等常见误区。
请详细说明ArrayList和LinkedList的区别,包括它们的底层实现、性能特点和使用场景。
ArrayList和LinkedList是Java中两种常用的List实现,它们在底层实现、性能特点和使用场景上有显著差异。ArrayList基于动态数组实现,具有O(1)的随机访问性能,但插入/删除操作需要移动元素,时间复杂度为O(n);LinkedList基于双向链表实现,随机访问性能为O(n),但插入/删除操作只需修改指针,时间复杂度为O(1)。ArrayList适合读多写少、需要频繁随机访问的场景;LinkedList适合写多读少、需要频繁在头部或中间插入/删除的场景,同时它还实现了Deque接口,可作为队列或双端队列使用。在实际开发中,ArrayList的使用频率更高,因为大多数场景下随机访问的需求更常见,且内存效率更高。
HashMap的底层原理是什么?它是线程安全的吗?在多线程环境下会遇到什么问题?如果要保证线程安全应该使用什么?ConcurrentHashMap是怎么保证线程安全的?请详细说明。
HashMap基于数组+链表/红黑树实现,通过哈希函数计算元素位置,使用链地址法解决哈希冲突。HashMap是非线程安全的,多线程环境下可能导致死循环、数据覆盖等问题。线程安全的替代方案包括Hashtable、Collections.synchronizedMap()和ConcurrentHashMap。ConcurrentHashMap在JDK 1.7采用分段锁实现,JDK 1.8改用CAS+synchronized,锁粒度更细,并发性能更好。
Java中的集合框架(Collection & Map)有哪些主要接口和实现类?
Java集合框架主要分为Collection和Map两大体系。Collection体系包括List(有序可重复,如ArrayList、LinkedList)、Set(无序不可重复,如HashSet、TreeSet)和Queue(队列,如PriorityQueue、ArrayDeque)。Map体系存储键值对,主要实现类有HashMap、LinkedHashMap、TreeMap、Hashtable和ConcurrentHashMap等。不同集合类在底层结构、有序性、线程安全、时间复杂度等方面有不同特性,应根据具体需求选择合适的实现类。
请详细介绍一下你参与过的项目,包括项目背景、你的职责以及使用的技术栈。
面试者需要清晰介绍参与过的项目,包括项目背景、个人职责、使用的技术栈、遇到的挑战及解决方案,以及项目成果和个人收获。重点突出自己在项目中的具体贡献、技术选型的思考过程、解决问题的思路以及从中获得的成长。回答应结构清晰,重点突出,体现技术深度和解决问题的能力。