需求:某电影院出售某些电影的票(复联3,红高粱....),有三个窗口同时进行售票(100张票),请您设计一个程序,模拟电影院售票
两种方式:
继承
接口
(1)synchronized实现
public class SellTicketDemo {
public static void main(String[] args) {//创建资源类对象(共享资源类/目标对象) SellTicket st = new SellTicket() ; //创建线程类对象 Thread t1 = new Thread(st, "窗口1") ; Thread t2 = new Thread(st ,"窗口2") ; Thread t3 = new Thread(st, "窗口3") ; //启动线程 st1.start(); st2.start(); st3.start();}
}
public class SellTicket implements Runnable {
//定义100张票private int tickets = 100 ;private Object obj = new Object() ;@Overridepublic void run() { while(true) { //new Object():锁对象 (门和关) //t1,t2,t3 synchronized(obj) {//t1进来,门一关,t2,t3进不来了 if(tickets>0) { try { //睡眠:延迟 Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() +"正在出售第"+(tickets--)+"张票");//0,-1 } } }}
}
(2)Lock实现
//测试类
public class SellTicketDemo {
public static void main(String[] args) { SellTicket st = new SellTicket() ; Thread t1 = new Thread(st,"窗口1") ; Thread t2 = new Thread(st,"窗口2") ; Thread t3 = new Thread(st,"窗口3") ; //启动线程 t1.start(); t2.start(); t3.start();}
}
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class SellTicket implements Runnable {
// 定义票private int tickets = 100;// Object obj = new Object();// Jdk5.0以后,java提供了一个具体的锁: 接口:Lockprivate Lock lock= new ReentrantLock(); //显示获取锁的前提,一定要创建Lock接口对象@Overridepublic void run() { while (true) { try { //try...finally lock.lock(); // 获取锁 syncrhonized(obj) if (tickets > 0) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "正在出售第" + (tickets--) + "张票"); } } finally {//释放锁 if(lock!=null) { lock.unlock(); } } }}
}
点击查看更多内容
1人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦