Java 利用佇列和多執行緒的思想完成使用者排隊買票。
阿新 • • 發佈:2019-01-13
要求:可以通過ArrayList或LinkedList介面完成佇列的建立,可以實現入隊、出隊等操作。新定義類利用多執行緒的思想完成買票和賣票的同步操作。
程式碼:
import java.util.ArrayList; import java.util.EmptyStackException; import java.util.LinkedList; import java.util.List; class Goods { private String goodsName;//商品名稱 MyQueue q = new MyQueue(); public synchronized void setGoods(String goodsName) {//生產商品方法 //當前還有商品需要等待消費者消費後才生產 while (q.size() > 0){ try { System.out.println("正在售票。。。"); wait(); } catch (InterruptedException e) { e.printStackTrace(); } } try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } this.goodsName = goodsName; q.add("票"); System.out.println(Thread.currentThread().getName()+"生產" + toString()); //生產完後喚醒 notifyAll(); } public synchronized void getGoods() {//消費商品方法 while (q.size() == 0){ try { System.out.println("賣完了。"); wait(); } catch (InterruptedException e) { e.printStackTrace(); } } try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } q.remove(); System.out.println(Thread.currentThread().getName()+"消費" + toString()); //消費完後,告訴生產者生產 notifyAll(); } @Override public String toString() { return "Goods{" + "goodsName='" + goodsName + '\'' + ", count=" + q.size() + '}'; } } //生產者 class Producer implements Runnable { private Goods goods; public Producer(Goods goods) { this.goods = goods; } public void run() { while (true) { this.goods.setGoods("生產票"); } } } //消費者 class Consumer implements Runnable { private Goods goods; public Consumer(Goods goods) { this.goods = goods; } public void run() { while (true) { this.goods.getGoods(); } } } class MyQueue { private LinkedList<Object> link = new LinkedList<Object>(); public MyQueue() { } public void add(Object obj) {//新增元素 link.addLast(obj); } public Object remove() {//刪除元素 if (isEmpty()) { throw new EmptyStackException(); } return link.removeFirst(); } public int size(){//求長度 return link.size(); } public boolean isEmpty() {//判斷是不是空 return link.isEmpty(); } public void clear() {//清空 link.clear(); } } public class Queue { public static void main(String[] args) { Goods goods = new Goods(); //儲存生產消費者執行緒 List<Thread> list = new ArrayList<>(); Producer producer = new Producer(goods); Consumer consumer = new Consumer(goods); for(int i= 0;i<5;i++){ Thread thread = new Thread(producer,"生產者"+i); list.add(thread); } for (int i = 0;i<10;i++){ Thread thread = new Thread(consumer,"消費者"+i); list.add(thread); } for (Thread thread:list) { thread.start(); } } }