java定义随机数

今天弄个多线程的进程通信半天没成功,后来才发现是因为我定义岁数的时候,定义错误了,当做教训记录下。

首先写个是题目:编写一段生产者/消费者的Java代码,其中生产者每次生产1个0到1000之间的随机数,消费者则把该随机数打印出来。如果产生的随机数为0,则生产者、 消费者均退出运行。要求生产者、消费者均使用线程来实现。


public class Threads {

	public static void main(String[] args) {
		Human human = new Human();

		new Thread(new Pro(human)).start();
		new Thread(new Cos(human)).start();
	}

}

class Pro implements Runnable {
	private Human h;

	public Pro(Human h) {
		this.h = h;
		h.produce();
		System.out.println(h.getNum());
	}

	@Override
	public void run() {
		System.out.println(h.getNum());
		while (h.getNum() != 0) {
			h.produce();
		}
	}

}

class Cos implements Runnable {
	private Human h;

	public Cos(Human h) {
		this.h = h;
	}

	@Override
	public void run() {
		while (h.getNum() != 0) {
			h.consumer();
		}
	}

}

class Human {
	public boolean wait = true;
	public int num;

	public synchronized void produce() {
		while (!wait) {
			try {
				System.out.println("生产者等待。。。。");
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		num = (int) (Math.random() * 1000);
		System.out.println("生产者:" + num);
		wait = false;
		this.notifyAll();
	}

	public synchronized void consumer() {
		while (wait) {
			try {
				System.out.println("消费者等待。。。。");
				this.wait();
			} catch (InterruptedException e) {

				e.printStackTrace();
			}
		}
		System.out.println("消费者:" + num);
		wait = true;
		this.notifyAll();
	}

	public int getNum() {
		return this.num;
	}

}


这里生产者产生数的时候由于我刚开始定义这样num的值:


num = (int) Math.random() * 1000;

然后num一直为0,导致2个线程都停止了运行,就没有实现通信,然后我一行行的看了半天,才知道自己定义随机数错误了,应该这样写:

num = (int) (Math.random() * 1000);(产生0-1000之间的随机数)

要用括号把函数体封装,不然就相当于num=0,看来基本功还是很重要啊


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值