package com.weigu.xiaochuang.project;
package com.weigu.xiaochuang.project; import java.util.concurrent.Semaphore; import java.util.concurrent.locks.ReentrantLock; public class ResourceManage { private Semaphore semaphore; private boolean resourceArray[]; private ReentrantLock lock; //初始化操作--以前没这样写过,进行赋值的关系 public ResourceManage() { this.resourceArray = new boolean[10]; //存放厠所狀太 this.semaphore = new Semaphore(10, true);//控制10个共享资源的使用,使用先进先出的公平模式进行共享;公平模式的信号量,先来的先获得信号量 this.lock = new ReentrantLock(true);//公平模式的锁,先来的先选 for (int i = 0; i < resourceArray.length; i++) { resourceArray[i] = true; //初始化为资源可用的情况 } } public void useResource(int userId) { try{ semaphore.acquire(); int id = getResourceId();//占到一个坑 System.out.print("userId:"+userId+"正在使用资源,资源id:"+id+"\n"); Thread.sleep(100);//do something,相当于于使用资源 resourceArray[id] = true;//退出这个坑 }catch (InterruptedException e){ e.printStackTrace(); }finally { semaphore.release();//释放信号量,计数器加1 } } public int getResourceId() { int id = -1; try { lock.lock(); for (int i = 0; i < 10; i++) { if (resourceArray[i]) { resourceArray[i] = false; id = 1; break; } } } finally { lock.unlock(); } return id; } }
public class ResourceUser implements Runnable { private ResourceManage resourceManage; private int userId; public ResourceUser(ResourceManage resourceManage, int userId) { this.resourceManage = resourceManage; this.userId = userId; } @Override public void run() { System.out.print("userId:" + userId + "准备使用资源...\n"); resourceManage.useResource(userId); System.out.print("userId:" + userId + "使用资源完毕...\n"); } public static void main(String[] args) { ResourceManage resourceManage = new ResourceManage(); Thread[] threads = new Thread[100]; //创建100个线程,但是线程数组为空, for (int i = 0; i < 100; i++) { Thread thread = new Thread(new ResourceUser(resourceManage, i));//创建线程2,将任务加入到线程 threads[i] = thread; //将线程赋值给线程数组 } for (int i = 0; i < 100; i++) { Thread thread = threads[i]; //获取单个线程,进行启动线程 try { thread.start();//启动线程 } catch (Exception e) { e.printStackTrace(); } } } Semaphore的使用: Semaphore使用时需要先构建一个参数来指定共享资源的数量,Semaphore构造完成后即是获取Semaphore、共享资源使用完毕后释放Semaphore。 Semaphore semaphore = new Semaphore(10,true); semaphore.acquire();