生产者和消费者问题+java版

本文介绍了一个基于Java实现的无锁生产者消费者模式案例。该模式通过自定义的监视器类来协调生产者和消费者的运行,利用同步方法实现资源访问的互斥,并通过条件变量实现进程间的等待和通知机制。生产者不断生成数据,而消费者消费这些数据,两者通过共享内存进行通信。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.*;
public class nowaitpandc
{
 static int producespeed=200;
 static int consumespeed=200;
 public static void main(String[] args){
  if(args.length > 0)
   producespeed=Integer.parseInt(args[0]);
  if(args.length > 1)
   consumespeed = Integer.parseInt(args[1]);
  nowaitmonitor monitor = new nowaitmonitor();
  new nowaitproducer(monitor,producespeed);
  new nowaitconsumer(monitor,consumespeed);
  try{
   Thread.sleep(1000);
  }catch (InterruptedException e){}
 System.exit(0);
 }
 
}

class nowaitmonitor
{
 int token=-1;
 PrintWriter out = new PrintWriter(System.out,true);
 boolean valueset=false;
 synchronized int get(){
  if(!valueset){
   try{
    wait();
   }catch (InterruptedException e){}
  }
  valueset=false;
  out.println("Got : "+ token);
  notify();
  return token;
 }
 synchronized void set(int value){
  if(valueset){
   try{
   wait();
   }catch(InterruptedException e){}
  }
  valueset=true;
  token=value;
  out.println("Set : "+ token);
  notify();
 }
}

class nowaitproducer implements Runnable
{
 nowaitmonitor monitor;
 int speed;
 nowaitproducer (nowaitmonitor monitor,int speed){
  this.monitor=monitor;
  this.speed=speed;
  new Thread(this,"producer").start();
 }
 public void run(){
  int i=0;
  while(true){
   monitor.set(i++);
   try{
    Thread.sleep((int)(Math.random()*speed));
   }catch (InterruptedException e){}
  }
 }
}

class nowaitconsumer implements Runnable
{
 nowaitmonitor monitor;
 int speed;

 nowaitconsumer(nowaitmonitor monitor,int speed){
  this.monitor=monitor;
  this.speed= speed;
  new Thread(this,"consumer").start();
 }
 public void run(){
  while(true){
   monitor.get();
   try{
    Thread.sleep((int)(Math.random()*speed));
   }catch (InterruptedException e){}
  }
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值