今天弄个多线程的进程通信半天没成功,后来才发现是因为我定义岁数的时候,定义错误了,当做教训记录下。
首先写个是题目:编写一段生产者/消费者的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,看来基本功还是很重要啊