本帖最后由 麻仁博 于 2015-4-17 23:49 编辑
- /*
- * 模拟一个火车站卖票程序,需求5个窗口,需要多线程完成.
- */
- class Tickets implements Runnable
- {
- private final ReentrantLock lock = new ReentrantLock();
- private String name;
- Tickets(String name )
- {
- this.name=name;
- }
- @Override
- public void run()
- {
-
- while(true)
- {
-
- lock.lock();
-
-
-
- if (tic.hasNum())
- {
-
- System.out.println(name+"号窗口"+"卖出了1张票,还有票:"+tic.getNum());
-
- }
- else
- {
- break;
- }
-
- lock.unlock();
-
- }
- }
-
- }
- class tic
- {
- private static int num;
- public tic(int num)
- {
- tic.num=num;
-
- }
- public static int getNum()
- {
- return --num;
- }
- public static boolean hasNum()
- {
- if (num>0)
- {
- return true;
- }
- else
- {
-
- return false;
- }
-
- }
- public static void setNum(int num)
- {
- tic.num=num;
- }
-
- }
- public class Demo29 {
-
-
- public static void main(String[] args)
- {
- tic t=new tic(10);
-
-
- new Thread(new Tickets("1")).start();
- new Thread(new Tickets("2")).start();
- new Thread(new Tickets("3")).start();
- new Thread(new Tickets("4")).start();
- new Thread(new Tickets("5")).start();
- }
- }
复制代码 |
|