import java.util.concurrent.Semaphore;
class Test extends Thread{
public static final int ITERATION = 10;
public static Semaphore[] semas = new Semaphore[2];
private Semaphore[] m_semas = new Semaphore[2];
static {
semas[0] = new Semaphore(1);
semas[1] = new Semaphore(0);
}
private String toPrint;
public Test(String toPrint)
{
this.toPrint = toPrint;
if (toPrint.equals("ping"))
{
m_semas[0] = semas[0];
m_semas[1] = semas[1];
}
else
{
m_semas[0] = semas[1];
m_semas[1] = semas[0];
}
}
public void run (){
for (int i = 0;i < ITERATION;i++)
{
acquire();
System.out.println(i + " : " + toPrint);
release();
}
}
private void acquire()
{
m_semas[0].acquireUninterruptibly();
}
private void release()
{
m_semas[1].release();
}
public static void main(String[] args) throws InterruptedException{
Thread ping = new Test("ping");
Thread pong = new Test("pong");
ping.start();
pong.start();
ping.join();
pong.join();
System.out.println("Done!");
}
}
Semaphore 交替输出 ping pong
最新推荐文章于 2024-04-10 17:47:39 发布