首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java 線程同步:單緩衝區生產者消費者模式優化與隨機延遲觀察

     編輯:程式設計綜合問答

原始碼問題

單緩衝區 (`isEmpty` + `value`) 的 `wait/notify` 邏輯正確,但輸出過於規則 (生產-消費嚴格交替),**無法展示真實併發隨機性**,因無隨機延遲且單緩衝區強制同步。

改進:引入隨機休眠觀察併發效果


class Buffer {
    private int value;
    private boolean empty = true;
    public synchronized void put(int v) {
        while (!empty) { try { wait(); } catch (InterruptedException e) {} }
        value = v; empty = false; notifyAll();
    }
    public synchronized int get() {
        while (empty) { try { wait(); } catch (InterruptedException e) {} }
        empty = true; notifyAll(); return value;
    }
}

class Producer extends Thread {
    private Buffer buf; private Random rnd = new Random();
    public Producer(Buffer b) { buf = b; }
    public void run() {
        for (int i=1; i<=5; i++) {
            buf.put(i);
            System.out.println("Put: " + i);
            sleepRandom();
        }
    }
    void sleepRandom() { try { Thread.sleep(rnd.nextInt(500)); } catch (InterruptedException e) {} }
}

class Consumer extends Thread {
    private Buffer buf; private Random rnd = new Random();
    public Consumer(Buffer b) { buf = b; }
    public void run() {
        for (int i=1; i<=5; i++) {
            System.out.println("\t\tGet: " + buf.get());
            sleepRandom();
        }
    }
    void sleepRandom() { try { Thread.sleep(rnd.nextInt(500)); } catch (InterruptedException e) {} }
}

public class Main {
    public static void main(String[] args) {
        Buffer buf = new Buffer();
        new Producer(buf).start();
        new Consumer(buf).start();
    }
}

更標準:有界緩衝區 (Array/Queue) + 生產者消費者模式


class BoundedBuffer {
    private final Queue q = new LinkedList<>();
    private final int capacity;
    public BoundedBuffer(int cap) { capacity = cap; }
    public synchronized void put(int v) throws InterruptedException {
        while (q.size() == capacity) wait();
        q.offer(v); notifyAll();
    }
    public synchronized int get() throws InterruptedException {
        while (q.isEmpty()) wait();
        int v = q.poll(); notifyAll(); return v;
    }
}

關鍵差異

特性單緩衝區有界隊列緩衝區
併發度嚴格交替 (鎖步)生產/消費可各自批次運行
適用場景教學示範、極簡同步實際系統、高吞吐、解耦
觀察隨機性需額外 sleep天然呈現

建議:教學理解單槽 wait/notify 即可;實務專案直接用 `BlockingQueue` (如 `ArrayBlockingQueue`),JDK 內建、無鎖優化、支援超時、流式 API。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved