我正在学习一本 Java 书中的练习,练习是一个生产者和消费者问题,它在方法上使用“同步”键工作,并与线程一起工作。
如果可以的话我会分享我书中的练习图片:
书中的结局是:
放:1 得到:1 放:2 得到:2 放:3 得到:3 放:4 得到:4 放:5 得到:5
我的代码与书上的代码完全相同,但结果与非常大的数字不同,例如:
放:84172 得到:84172 放:84173 得到:84173 放:84174 得到:84174 放:84175 得到:84175 放:84176 得到:84176
或:
得到:116734 放:116735 得到:116735 放:116736 得到:116736 放:116737 得到:116737
等等……
如果我是正确的,我知道线程/多线程与 CPU 并驾齐驱。
问:我的 CPU 会不会是这么高的值的原因?因为太快了?
*我的 CPU 是:第 11 代 Intel(R) Core(TM) i7-1165G7 @ 2.80GHz
Q:如果以上问题的答案是否定的,你能帮我理解为什么我得到这么高的价值吗?
主要:
public class Main {
public static void main(String[] args) {
Q queue = new Q();
Producer producer = new Producer(queue);
Consumer consumer = new Consumer(queue);
producer.thread.start();
consumer.thread.start();
}
}
问:
public class Q {
int n;
boolean ready = false;
synchronized int get(){
while (!ready){
try {
wait();
} catch (InterruptedException e){
System.out.println("Consumer thread was interrupted!");
System.out.println();
System.out.println(e);
}
}
System.out.println("Got: " + n);
ready = false;
notify();
return n;
}
// ------------------------
synchronized void put(int n){
while (ready){
try {
wait();
} catch (InterruptedException e){
System.out.println("Consumer thread was interrupted!");
System.out.println();
System.out.println(e);
}
}
this.n = n;
ready = true;
System.out.println("Put: " + n);
notify();
}
}
制作人:
public class Producer implements Runnable{
Q queue;
Thread thread;
Producer(Q queue){
thread = new Thread(this, "Producer");
this.queue = queue;
}
@Override
public void run() {
int i = 0;
while (true){
queue.put(i++);
}
}
}
消费者:
public class Consumer implements Runnable{
Q queue;
Thread thread;
Consumer(Q queue){
thread = new Thread(this, "Consumer");
this.queue = queue;
}
@Override
public void run() {
while (true){
queue.get();
}
}
}
谢谢。