Java与Go: 生产者消费者模型
以下是Java和Go语言分别实现的生产者-消费者模型的简单示例。
Java 生产者消费者模型示例:
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class ProducerConsumerExample {
public static void main(String[] args) {
BlockingQueue<Integer> buffer = new LinkedBlockingQueue<>(10);
Producer producer = new Producer(buffer);
Consumer consumer = new Consumer(buffer);
new Thread(producer).start();
new Thread(consumer).start();
}
}
class Producer implements Runnable {
private final BlockingQueue<Integer> buffer;
public Producer(BlockingQueue<Integer> buffer) {
this.buffer = buffer;
}
@Override
public void run() {
try {
while (true) {
buffer.put(1);
System.out.println("Produced: " + 1);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
class Consumer implements Runnable {
private final BlockingQueue<Integer> buffer;
public Consumer(BlockingQueue<Integer> buffer) {
this.buffer = buffer;
}
@Override
public void run() {
try {
while (true) {
buffer.take();
System.out.println("Consumed: " + 1);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
Go 生产者消费者模型示例:
package main
import (
"fmt"
"sync"
"time"
)
type Buffer struct {
queue chan int
mux sync.Mutex
}
func NewBuffer(size int) *Buffer {
return &Buffer{
queue: make(chan int, size),
}
}
func (b *Buffer) Put(item int) {
b.mux.Lock()
defer b.mux.Unlock()
b.queue <- item
fmt.Println("Produced:", item)
}
func (b *Buffer) Take() int {
b.mux.Lock()
defer b.mux.Unlock()
item := <-b.queue
fmt.Println("Consumed:", item)
return item
}
type Producer struct {
buffer *Buffer
}
func (p *Producer) Run() {
for {
p.buffer.Put(1)
time.Sleep(1 * time.Second)
}
}
type Consumer struct {
buffer *Buffer
}
func (c *Consumer) Run() {
for {
c.buffer.Take()
time.
评论已关闭