54、实现多个公司售卖电影票功能
练习:使用多线程程序模拟电影票售卖的过程,一共有100张电影票,3个公司对外售卖
代码实现:
先创建一个Ticket类实现Runnable接口
package com.sutaoyu.Thread; public class test_6 { //100张电影票 private int count = 100; public void run(){ while(true) { synchronized(this) { // 同步 锁 if(count <= 0) { break; }else { //将电影票总数做自减运算 count--; System.out.println(Thread.currentThread().getName()+"卖出一张,剩余" + count + "张"); } } } } }
创建线程:
package com.sutaoyu.Thread; public class test_7 { public static void main(String[] args) { Ticket t = new Ticket(); Thread t1 = new Thread(t); Thread t2 = new Thread(t); Thread t3 = new Thread(t); t1.setName("猫眼电影"); t2.setName("糯米电影"); t3.setName("美团电影"); t1.start(); t2.start(); t3.start(); } }