请使用Semaphore编写一个程序,实现以下效果: * 要求: * 1.有10名游客要参观展览室, * 2.展览室同时只允许最多“三个游客”参观, * 3.每个游客参观时间2秒。
2021/12/20 1:20:33
本文主要是介绍请使用Semaphore编写一个程序,实现以下效果: * 要求: * 1.有10名游客要参观展览室, * 2.展览室同时只允许最多“三个游客”参观, * 3.每个游客参观时间2秒。,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
public class TestDemo { public static void main(String[] args) { //1.创建Semaphore对象 Semaphore semaphore = new Semaphore(3); //2.循环,开启10个线程 for (int i = 0; i < 10; i++) { new Thread() { @Override public void run() { try { // 获得参观权 semaphore.acquire(); System.out.println(Thread.currentThread().getName() + ":开始参观-" + LocalTime.now()); // 参观 2s Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } finally { // 释放参观权 semaphore.release(); } } }.start(); } } } ================================================ public class Test01 { public static void main(String[] args) { Semaphore s = new Semaphore(3); for (int i = 0; i < 10; i++) { MyThread myThread = new MyThread(s); myThread.start(); } } } ========================================================== public class MyThread extends Thread { public Semaphore s; public MyThread(Semaphore s) { this.s = s; } @Override public void run() { try { s.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(getName()+":"+"在参观"); s.release(); } }
这篇关于请使用Semaphore编写一个程序,实现以下效果: * 要求: * 1.有10名游客要参观展览室, * 2.展览室同时只允许最多“三个游客”参观, * 3.每个游客参观时间2秒。的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?