多线程同步问题:Java中CountDownLatch、Semaphore用法示例
CountDownLatch
和Semaphore
是Java中两种常用的线程同步工具,主要用于控制多个线程的执行顺序。
CountDownLatch
示例:
```java
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
private CountDownLatch countDownLatch = new CountDownLatch(3);
public void threadAction() throws InterruptedException {
System.out.println("Thread-1 starting...");
countDownLatch.await();
System.out.println("Thread-1 completed!");
// Thread 2 and 3 same process
System.out.println("Thread-2 starting...");
countDownLatch.await();
System.out.println("Thread-2 completed!");
System.out.println("Thread-3 starting...");
countDownLatch.await();
System.out.println("Thread-3 completed!");
}
public static void main(String[] args) {
CountDownLatchExample example = new CountDownLatchExample();
Thread thread1 = new Thread(example::threadAction));
Thread thread2 = new Thread(example::threadAction));
Thread thread3 = new Thread(example::threadAction));
thread1.start();
thread2.start();
thread3.start();
}
}
在这个例子中,我们创建了一个`CountDownLatch`实例,初始计数为3。然后在3个线程中调用`await()`方法,来等待计数器下降到0。
2. `Semaphore`示例:
```java
import java.util.concurrent.Semaphore;
public class SemaphoreExample {
private Semaphore semaphore = new Semaphore(5); // 初始化允许的最大并发数量为5
public void threadAction() {
try {
semaphore.acquire(); // 请求一个许可证
System.out.println("Thread-1 starting...");
// 线程执行逻辑
Thread.sleep(2000);
System.out.println("Thread-1 completed!");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release(); // 释放一个许可证
}
}
public static void main(String[] args) {
SemaphoreExample example = new SemaphoreExample();
Thread thread1 = new Thread(example::threadAction));
Thread thread2 = new Thread(example::threadAction));
thread1.start();
thread2.start();
}
}
在这个例子中,我们创建了一个Semaphore
实例,初始值为5。每个线程请求许可证(调用acquire()
)时,如果当前许可数量大于0,则允许请求,并减少许可数量;否则线程会阻塞,直到有其他线程释放了许可证。
以上就是Java中CountDownLatch和Semaphore两种同步工具的简单使用示例。
还没有评论,来说两句吧...