标签:generate 改进 号码 void 自己的 ali err ola int
以前有个习惯就是发现一些生活的系统,总会大概想想自己开发到底怎么实现。有的可能就在脑海里面过一下思路,有的则会写个简单的demo验证一下自己的思路是否可行。
笔者前段时间在医院等候,仔细观察了一下叫号系统。于是有了想自己写一个简单的叫号系统。
用例大致如下:
程序大致如下:
Worker.java
1 package demo; 2 3 import java.util.concurrent.locks.Lock; 4 import java.util.concurrent.locks.ReentrantLock; 5 6 public class Worker implements Runnable { 7 private static int counter = 0; 8 private Lock myLock = new ReentrantLock(); 9 private volatile boolean isWorking = true; 10 11 @Override 12 public void run() { 13 while (isWorking) { 14 myLock.lock(); 15 ++counter; 16 // 开始叫号,当前号(counter)患者进入某个诊室 17 String doctor = Thread.currentThread().getName(); 18 int currentNO = counter; // 保留当前医生的病人号码 19 System.out.println(doctor + " is calling patient NO --- "+currentNO); 20 myLock.unlock(); 21 try { 22 long checkTime = (long)(10000 * Math.random()); 23 Thread.sleep(checkTime); 24 System.out.println(doctor + " used " + checkTime + " milliseconds on patient NO --- "+currentNO); 25 // 医生看病时间结束,开始叫下一位患者 26 System.out.println(doctor + " has finished diagnosing patient NO--- "+currentNO); 27 System.out.println("============================================"); 28 } catch (InterruptedException e) { 29 // TODO Auto-generated catch block 30 e.printStackTrace(); 31 } 32 } 33 } 34 35 // 所有医生下班了 36 public void stop() { 37 isWorking = false; 38 } 39 }
主类Yell.java
package demo; public class Yell { public static void main(String[] args) {
//模拟三个医生Alice, Tom, Bob Worker runner = new Worker(); Thread t1 = new Thread(runner); t1.setName("Alice"); t1.start(); Thread t2 = new Thread(runner); t2.setName("Tom"); t2.start(); Thread t3 = new Thread(runner); t3.setName("Bob"); t3.start(); try { Thread.sleep(20000); // 模拟某个医生下班中途退出, 这里的退出有待进一步改进 t1.stop(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { Thread.sleep(20000); // 所有医生下班了 runner.stop(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
标签:generate 改进 号码 void 自己的 ali err ola int
原文地址:https://www.cnblogs.com/sankt/p/9277833.html