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 }
原创文章,转载请说明出处,谢谢合作