type
status
date
slug
summary
tags
category
icon
password
主要思路是生产者消费者。当A线程打印到第5个时,让B线程的信号量加1;B线程开始执行并结束,结束前让A线程的信号量加1,A线程继续add
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Semaphore;
public class TwoAddLearn {
public static void main(String[] args) {
Container container = new Container();
Semaphore semaphoreA = new Semaphore(0);
Semaphore semaphoreB = new Semaphore(0);
ThreadA threadA = new ThreadA(container, semaphoreA, semaphoreB);
ThreadB threadB = new ThreadB(container, semaphoreA, semaphoreB);
threadA.start();
threadB.start();
}
}
class Container {
private List<Integer> list = new LinkedList<>();
public void add(Integer a) {
list.add(a);
}
public int getSize() {
return list.size();
}
}
class ThreadA extends Thread {
private Container container;
private Semaphore semaphoreA;
private Semaphore semaphoreB;
ThreadA(Container container, Semaphore semaphoreA, Semaphore semaphoreB) {
this.container = container;
this.semaphoreA = semaphoreA;
this.semaphoreB = semaphoreB;
}
@Override
public void run() {
super.run();
for (int i = 1; i <= 10; i++) {
if (container.getSize() == 5) {
semaphoreB.release();
try {
semaphoreA.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(i);
container.add(i);
}
}
}
class ThreadB extends Thread {
private Container container;
private Semaphore semaphoreA;
private Semaphore semaphoreB;
ThreadB(Container container, Semaphore semaphoreA, Semaphore semaphoreB) {
this.container = container;
this.semaphoreA = semaphoreA;
this.semaphoreB = semaphoreB;
}
@Override
public void run() {
super.run();
try {
semaphoreB.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程B结束");
semaphoreA.release();
}
}
执行结果

- 作者:比尔盖子
- 链接:https://www.connorshen.site/article/19af7748-71e2-464d-bbe7-5ab7c936febe
- 声明:本文采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。