1. 程式人生 > 其它 >阿里雲面試題:生產者和消費者模型

阿里雲面試題:生產者和消費者模型

某次面試阿里雲,要求實時寫一個小程式,要求如下:
1.兩個執行緒,一個執行緒生產者,一個執行緒是消費者
2.生產者生產票,超過10張就休息,被消費了就繼續生產。
3.消費者消費票,票沒了之後就休息,有票了接著消費。
題目看著很簡單,但卻包含了很多考點:訊息佇列、執行緒、執行緒通訊、鎖。
具體看看我寫的原始碼,這是後期幾經修改後的內容。

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * 某次面試阿里雲,要求實時寫一個小程式,要求如下:
 * 1.兩個執行緒,一個執行緒生產者,一個執行緒是消費者
 * 2.生產者生產票,超過10張就休息,被消費了就繼續生產。
 * 3.消費者消費票,票沒了之後就休息,有票了接著消費。
 * 題目看著很簡單,但卻包含了很多考點:訊息佇列、執行緒、執行緒通訊、鎖。
 * 具體看看我寫的原始碼,這是後期幾經修改後的內容。
 
*/ public class Test { private static Queue queue = new ConcurrentLinkedQueue(); private static Object lock = new Object(); public static void main(String[] args) { //生產者執行緒 Thread p = new Thread(new Runnable() { @Override public void run() {
while (true) { queue.add("piao"); System.out.println(Thread.currentThread().getName() + ":加票...餘票有" + queue.size() + "張"); synchronized (lock) { //每次生產完了之後通知一下等待中的消費者 lock.notify();
if (queue.size() >= 10) { System.out.println(Thread.currentThread().getName() + ":票加滿了"); try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } } } }, "Provider"); Thread c = new Thread(new Runnable() { @Override public void run() { while (true) { String ticket = (String) queue.poll(); System.out.println(Thread.currentThread().getName() + ":取票...餘票有" + queue.size() + "張"); try { Thread.sleep(500L); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (lock) { //每次消費完了之後通知一下等待中的生產者 lock.notify(); if (ticket == null) { System.out.println(Thread.currentThread().getName() + ":票沒有了"); try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } }, "Comsumer"); p.start(); try { Thread.sleep(300L); } catch (InterruptedException e) { e.printStackTrace(); } c.start(); } }