需求:某电影院出售某些电影的票(复联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() ;
@Override
public 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提供了一个具体的锁: 接口:Lock
private Lock lock= new ReentrantLock(); //显示获取锁的前提,一定要创建Lock接口对象
@Override
public 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();
}
}
}
}
}
原文地址:http://blog.51cto.com/13670525/2122468
时间: 2024-11-09 03:07:47