在Java中,确保多线程顺序执行可以通过以下几种方法实现:
使用`join()`方法
通过调用线程的`join()`方法,可以确保当前线程等待指定的线程执行完毕后,再继续执行当前线程。
```java
Thread thread1 = new Thread(() -> {
System.out.println("线程A");
});
Thread thread2 = new Thread(() -> {
try {
thread1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程B");
});
thread1.start();
thread2.start();
使用`CountDownLatch`
`CountDownLatch`允许一个或多个线程等待其他线程完成操作。```javaCountDownLatch latch = new CountDownLatch(1);
new Thread(() -> {
System.out.println("线程A");
latch.countDown();
}).start();
new Thread(() -> {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程B");
}).start();
使用`Semaphore`信号量
`Semaphore`可以用来控制对共享资源的访问,确保线程按顺序获取许可并执行。

```java
Semaphore semaphore = new Semaphore(1);
new Thread(() -> {
try {
semaphore.acquire();
System.out.println("线程A");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}).start();
new Thread(() -> {
try {
semaphore.acquire();
System.out.println("线程B");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}).start();
使用`BlockingQueue`
`BlockingQueue`提供了线程安全的队列,可以用于线程间的协调,按顺序执行任务。```javaBlockingQueue
queue = new LinkedBlockingQueue<>(); new Thread(() -> {
try {
queue.put("线程A");
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
String task = queue.take();
System.out.println(task);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
使用`Lock`和`Condition`
`Lock`和`Condition`可以用来控制线程的执行顺序,使线程在特定条件下等待或唤醒。
```java
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
new Thread(() -> {
lock.lock();
try {
System.out.println("线程A");
condition.await();
System.out.println("线程B");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}).start();
new Thread(() -> {
lock.lock();
try {
System.out.println("线程C");
condition.signal();
} finally {
lock.unlock();
}
}).start();
使用`CyclicBarrier`
`CyclicBarrier`可以让一组线程等待至某种状态后全部执行。
