黑马程序员技术交流社区
标题:
大侠你在哪里?这个题死磕不出来啊?求支招
[打印本页]
作者:
微小山
时间:
2014-12-19 09:15
标题:
大侠你在哪里?这个题死磕不出来啊?求支招
大侠你在哪里?昨做了一下面试题,发现这个死磕不出来啊,有木有大侠支支招!感激不尽!编写三各类Ticket、SealWindow、TicketSealCenter分别代表票信息、售票窗口、售票中心。售票中心分配一定数量的票,由若干个售票窗口进行出售,利用你所学的线程知识来模拟此售票过程。
作者:
后悔药
时间:
2014-12-19 12:04
本帖最后由 后悔药 于 2014-12-19 15:28 编辑
原来早上回的是这个帖子,不好意思我没看到“售票中心分配一定数量的票”,重新敲了一遍,
<div class="blockcode"><blockquote>public class Test4 {
public static void main(String[] args) {
Ticket ticket = new Ticket("芜湖", 0);
TicketSealCenter tsc1 = new TicketSealCenter(ticket);
SealWindow sw1 = new SealWindow(ticket);
SealWindow sw2 = new SealWindow(ticket);
SealWindow sw3 = new SealWindow(ticket);
// SealWindow sw4 = new SealWindow(ticket);<p style="line-height: 30px; text-indent: 2em;"></p>
Thread th1 = new Thread(tsc1);
th1.setName("售票中心");
Thread th2 = new Thread(sw2);
th2.setName("售票窗口1");
Thread th3 = new Thread(sw1);
th3.setName("售票窗口2");
Thread th4 = new Thread(sw3);
th4.setName("售票窗口3");
th1.start();
th2.start();
th3.start();
th4.start();
}
}
class SealWindow implements Runnable {
private Ticket ticket;
public SealWindow(Ticket ticket) {
this.ticket = ticket;
}
@Override
public void run() {
while (true) {
ticket.seal();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class TicketSealCenter implements Runnable {
private Ticket t;
public TicketSealCenter(Ticket t) {
this.t = t;
}
@Override
public void run() {
while (true) {
// 生产芜湖车次的车票
t.pro("芜湖");
}
}
}
class Ticket {
static LinkedList<Ticket> pool = new LinkedList<Ticket>();
private String destination;
private int site = 0;
public Ticket(String destination, int site) {
this.destination = destination;
this.site = site;
}
private boolean flag = false;
private Lock lock = new ReentrantLock();
private Condition con_pro = lock.newCondition();
private Condition con_seal = lock.newCondition();
public void pro(String des) {
lock.lock();
try {
while (flag) {
con_pro.await();
}
//每次生产若干票
int num = (int) (Math.random() * 10)+1;
for (int i = 0; i < num; i++) {
Ticket t = new Ticket(des, site++);
pool.addFirst(t);
System.out.println(Thread.currentThread().getName() + "生产了"
+ t.toString());
}
flag = true;
con_seal.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
/**
* 这个方法被若干线程操作
*/
public void seal() {
lock.lock();
try {
while (!flag) {
con_seal.await();
}
if (pool.size() > 0) {
// 如果有票,售票窗口就开始卖票并打印信息
System.out.println(Thread.currentThread().getName() + "售出了"
+ pool.removeLast().toString());
} else {
// 如果没有有票,唤醒售票中心线程生产票
flag = false;
con_pro.signal();
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
@Override
public String toString() {
// destination车次第site座
return destination + "车次第" + site + "座";
}
}
复制代码
作者:
Seejun
时间:
2014-12-19 19:43
楼上好腻害
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2