zoukankan      html  css  js  c++  java
  • Java 多线程实现多窗口同时售票简单功能

     1 package day162020072701.day1603;
     2 
     3 import java.util.concurrent.locks.Lock;
     4 import java.util.concurrent.locks.ReentrantLock;
     5 
     6 /**
     7  * @author liuwenlong
     8  * @create 2020-07-27 13:13:32
     9  */
    10 @SuppressWarnings("all")
    11 public class SellTicke implements Runnable {
    12    private int tik = 10;
    13     Lock lock = new ReentrantLock();
    14 
    15     @Override
    16     public void run() {
    17         while (true) {
    18             //加锁
    19             lock.lock();
    20             if (tik > 0) {
    21                 try {
    22                     //模拟一下出票过程
    23                     Thread.sleep(100);
    24                 } catch (InterruptedException e) {
    25                     e.printStackTrace();
    26                 }
    27                 System.out.println(Thread.currentThread().getName() + ";还剩" + --tik + "张票");
    28             }
    29             //解锁
    30             lock.unlock();
    31         }
    32     }
    33 }
     1 package day162020072701.day1603;
     2 
     3 /**
     4  * @author liuwenlong
     5  * @create 2020-07-27 13:15:03
     6  */
     7 @SuppressWarnings("all")
     8 public class TestSell {
     9     public static void main(String[] args) throws InterruptedException {
    10         SellTicke s = new SellTicke();
    11         Thread t1 = new Thread(s,"窗口1");
    12         Thread t2 = new Thread(s,"窗口2");
    13         Thread t3 = new Thread(s,"窗口3");
    14         t1.start();
    15         t2.start();
    16         t3.start();
    17     }
    18 }

  • 相关阅读:
    多态
    没有抽象方法的抽象类有什么意义
    抽象类继承(雇员练习)
    怎样在win7中 安装Tomcat7.0
    继承训练
    Java的接口和抽象类
    jQuery插件的学习
    jQuery学习之路-A
    android之路-android事件处理-OnTouchListener
    丢弃的东西,还能否找回?
  • 原文地址:https://www.cnblogs.com/lwl80/p/13387088.html
Copyright © 2011-2022 走看看