扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
import java.util.concurrent.Semaphore;

public class Mutex ...{
private Semaphore s = new Semaphore(1);

public void acquire() throws InterruptedException ...{
s.acquire();
}
public void release()...{
s.release();
}
public boolean attempt(int ms) throws InterruptedException ...{
return s.tryAcquire(ms);
}
}

public class TestMutex ...{
public static void main(String[] args) throws InterruptedException...{
Mutex mutex=new Mutex();
mutex.acquire();
mutex.release();
mutex.release();
new MyThread(mutex).start();
new MyThread(mutex).start();
}
}

class MyThread extends Thread...{
private Mutex mutex;

public MyThread(Mutex mutex) ...{
this.mutex=mutex;
}

public void run()...{
try ...{
mutex.acquire();
} catch (InterruptedException e1) ...{
throw new RuntimeException(e1);
}
for(int i=0;i<10;i++)...{
System.out.print(i);
if(i%3==0)...{
try ...{
Thread.sleep(100);
} catch (InterruptedException e) ...{
e.printStackTrace();
}
}
}
mutex.release();
}
} 该程序的输出如下:
00123123456456789789
从而证实了我的猜测。
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。