package com.company;
import java.util.concurrent.*;
public class PrintABCSemaphore {
Semaphore s1=new Semaphore(0);
Semaphore s2=new Semaphore(0);
Semaphore s3=new Semaphore(1);
public void PirntA()throws InterruptedException
{
for(int i=0;i<10;i++)
{
s3.acquire();
System.out.print("a");
s2.release();
}
}
public void PirntB()throws InterruptedException
{
for(int i=0;i<10;i++)
{
s2.acquire();
System.out.print("b");
s1.release();
}
}
public void PirntC()throws InterruptedException
{
for(int i=0;i<10;i++)
{
s1.acquire();
System.out.print("c");
s3.release();
}
}
public static void main(String[] args)
{
PrintABCSemaphore t=new PrintABCSemaphore();
ExecutorService ex=new ThreadPoolExecutor(3,Integer.MAX_VALUE,60L, TimeUnit.SECONDS,
new SynchronousQueue<>());
ex.execute(()-> {
try {
t.PirntA();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
ex.execute(()-> {
try {
t.PirntB();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
ex.execute(()-> {
try {
t.PirntC();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}
用信号量实现循环打印ABC
最新推荐文章于 2023-04-03 19:58:01 发布