需求是这样的
两个线程执行任务,但是有要求,必须是A执行完毕 再执行B 交叉执行!
先上代码:
(改造前)
public class Fangzh {
private int n;
public Fangzh(int n) {
this.n = n;
}
public void eat(){
for (int i = 0; i < n; i++) {
System.out.println("吃饭");
}
}
public void sleep() {
for (int i = 0; i < n; i++) {
System.out.println("睡觉");
}
}
}
public static void main(String[] args) {
Fangzh fooBar = new Fangzh(5);
new Thread(()->{fooBar.eat();}).start();
new Thread(()->{fooBar.sleep();}).start();
}
输出结果:

这有问题啊!
改造后
public class Fangzh {
Semaphore eat = new Semaphore(1, true);
Semaphore sleep = new Semaphore(0, true);
int n =0;
public Fangzh(int n) {
this.n = n;
}
public void eat(){
for (int i = 0; i < n; i++) {
try {
eat.acquire();
System.out.println("吃饭");
sleep.release();
}catch (Exception e){
e.printStackTrace();
}
}
}
public void sleep() {
for (int i = 0; i < n; i++) {
try {
sleep.acquire();
System.out.println("睡觉");
eat.release();
}catch (Exception e){
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Fangzh fooBar = new Fangzh(5);
new Thread(()->{
fooBar.eat();
}).start();
new Thread(()->{
fooBar.sleep();
}).start();
}

##知识点 Semaphore