本帖最后由 徐升2013 于 2013-4-15 17:03 编辑
- /*7、 编写三各类Ticket、SealWindow、TicketSealCenter分别代表票信息、售票窗口、售票中心。
- * 售票中心分配一定数量的票,由若干个售票窗口进行出售,利用你所学的线程知识来模拟此售票过程。
- *
- *
- */
- public class Test7 {
- public static void main(String[] args) {
- Prodrucer p1 = new Prodrucer("北京--上海", 1);
- SealWindow s1 = new SealWindow();
- Thread t1 = new Thread(p1, "生产者1");
- Thread t2 = new Thread(p1, "生产者2");
- Thread t3 = new Thread(s1, "售票窗口1");
- Thread t4 = new Thread(s1, "售票窗口2");
- Thread t5 = new Thread(s1, "售票窗口3");
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- t5.start();
- }
- }
- class SealWindow implements Runnable {
- private TicketSealCenter tt = null;
- SealWindow() {
- tt = TicketSealCenter.getInstance();
- }
- @Override
- public void run() {
- tt.put();
- }
- }
- class Prodrucer implements Runnable {
- private TicketSealCenter tt = null;
- private Ticket t = null;
- Prodrucer(String name, int ID) {
- t = Ticket.getInstance();
- tt = TicketSealCenter.getInstance();
- t.setId(ID);
- t.setName(name);
- }
- @Override
- public void run() {
- tt.make();
- }
- }
- class TicketSealCenter {
- private Ticket t = null;
- private boolean flag = false;
- private Lock lock = new ReentrantLock();
- private Condition m = lock.newCondition();
- private Condition p = lock.newCondition();
- private TicketSealCenter() {
- t = Ticket.getInstance();
- }
- private static final TicketSealCenter tt = new TicketSealCenter();
- public static TicketSealCenter getInstance() {
- return tt;
- }
- public void make() {
- lock.lock();
- try {
- while (true) {
- if (flag)
- m.await();
- System.out.println("生产了一张信息为:" + t.toString() + "的票.");
- flag = true;
- p.signal();
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- } finally {
- lock.unlock();
- }
- }
- public void put() {
- lock.lock();
- try {
- while (true) {
- if (!flag)
- p.await();
- System.out.println("出售了一张:" + t.getName() + "的票,Id为:"
- + t.getId());
- flag = false;
- m.signal();
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- } finally {
- lock.unlock();
- }
- }
- }
- class Ticket {
- private String name;
- private int id = 1;
- private static final Ticket ticket = new Ticket("请设置票的名字", 1);
- private Ticket(String name, int id) {
- this.name = name;
- this.id = id;
- }
- public static Ticket getInstance() {
- return ticket;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String toString() {
- id++;
- return this.getName() + "......" + this.getId();
- }
- }
复制代码 为什么加锁后还是会出现错号的现象呢?该怎么优化才可以? |