实现多窗口售票的两种方式
继承的方式实现多窗口售票
TestWindow1
package com.aff.thread; public class TestWindow { //继承的方式实现多窗口售票
//存在线程安全性问题,后面给出解决方法
public static void main(String[] args) { Window w1 = new Window(); Window w2 = new Window(); Window w3 = new Window(); w1.setName("窗口1"); w2.setName("窗口2"); w3.setName("窗口3"); w1.start(); w2.start(); w3.start(); } } class Window extends Thread{ static int ticket = 100; public void run(){ while(true){ if(ticket>0){ System.out.println(Thread.currentThread().getName()+"售票,票号为:"+ ticket--); }else{ break; } } } }
实现的方式实现多窗口售票
TestWindow1
package com.aff.thread; //使用实现Runnable接口的方式,售票
//此程序存在线程安全问题:打印车票时,会出现重票,错票
public class TestWindow1 { public static void main(String[] args) { Window1 w = new Window1(); Thread t1 = new Thread(w); Thread t2 = new Thread(w); Thread t3 = new Thread(w); t1.setName("窗口1"); t2.setName("窗口2"); t3.setName("窗口3"); t1.start(); t2.start(); t3.start(); } } class Window1 implements Runnable { int ticket = 100; @Override public void run() { while (true) { if (ticket > 0) { System.out.println(Thread.currentThread().getName() + "售票,票号为:" + ticket--); } else { break; } } } }
All that work will definitely pay off