1. 如何用java解决:启动三个线程,依次打印“A”, “B”, “C” ?
2. Semaphore 理解:
可用于控制并发数量,即同时访问特定资源的线程数量,通过协调各个线程,保证合理使用公共资源。
比如以数据库连接池为例,现有30个线程请求数据库连接,但连接池的最大连接数为10,故会有20个线程请求失败。为控制连接数,可用Semaphore操作。
Semaphore 中有个计数器,表示可用的许可证数量。 调用acquire()方法,可以获取许可证,使用完后调用release()方法,释放许可证。
3. code :
package com.nami.algorithm.study.thread;
import java.util.concurrent.Semaphore;
/**
* 描述: 使用信号量解决 依次打印ABC问题
*
* @Author: lbc
* @Date: 2024-02-22 14:35
* @email: 594599620@qq.com
* @Description: keep coding
*/
public class ABCPrintingWithSemaphore {
private static Semaphore a = new Semaphore(1);
private static Semaphore b = new Semaphore(0);
private static Semaphore c = new Semaphore(0);
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
while (true) {
try {
a.acquire();
System.out.println("A");
b.release();
} catch (Exception e) {
}
}
}, "t1");
Thread t2 = new Thread(() -> {
while (true) {
try {
b.acquire();
System.out.println("B");
c.release();
} catch (Exception e) {
}
}
}, "t2");
Thread t3 = new Thread(() -> {
while (true) {
try {
c.acquire();
System.out.println("C");
a.release();
} catch (Exception e) {
}
}
}, "t3");
t1.start();
t2.start();
t3.start();
}
}