gpt4 book ai didi

java - 生产者消费者多线程为什么需要Thread.sleep?

转载 作者:行者123 更新时间:2023-11-30 11:28:22 26 4
gpt4 key购买 nike

虽然我确实理解线程间通信的要点以及在监视器上等待和通知的用法以确保 Put/Get 操作同步 - 我试图理解为什么我们需要 Thread.sleep() 当我们有一个有效的等待/通知机制时,生产者和消费者在下面的代码中?如果我删除 thread.sleep() - 输出会变得糟糕!

import java.io.*;
import java.util.*;

public class Test {
public static void main(String argv[]) throws Throwable {

Holder h = new Holder();
Thread p = new Thread(new Producer(h), "Producer");
Thread c = new Thread(new Consumer(h), "Consumer");
p.start();
c.start();
}
}

class Holder {
int a;
volatile boolean hasPut;

public synchronized void put(int i) {
while (hasPut) {
try {
System.out.println("The thread " + Thread.currentThread().getName() + " Going ta sleep...");
wait(1000);
} catch(Exception e) {
e.printStackTrace();
}
}
this.a = i;
hasPut = true;
notifyAll();
}

public synchronized int get() {
while (!hasPut) {
try {
System.out.println("The thread " + Thread.currentThread().getName() + " Going ta sleep...");
wait(1000);
} catch(Exception e) {
e.printStackTrace();
}
}
hasPut = false;
notifyAll();
return this.a;
}
}

class Producer implements Runnable {
Holder h;
public Producer(Holder h) {
this.h = h;
}

public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("Putting : "+i);
h.put(i);
try {
Thread.sleep(10);
} catch (InterruptedException ie) {
}
}
}
}

class Consumer implements Runnable {
Holder h;
public Consumer(Holder h) {
this.h = h;
}

public void run() {
for (int i = 0; i < 1000; i++) {
int k = h.get();
System.out.println("Getting : "+k);
try {
Thread.sleep(10);
} catch (InterruptedException ie) {
}
}
}
}

最佳答案

我认为您对控制台输出感到困惑。

重要的部分是消费者中的每个 .get() 是否都从生产者那里获取所有元素。当您删除所有令人困惑的 System.out. 行并仅使用

class Consumer implements Runnable {
Holder h;
public Consumer(Holder h) {
this.h = h;
}

public void run() {
for (int i = 0; i < 1000; i++) {
int k = h.get();
if (k != i)
System.out.println("Got wrong value " + k + "expected value " + i);
}
}
}

您会发现您的代码工作正常。

我认为你的困惑来自于看起来像这样的输出

Getting : 990
Putting : 993
Getting : 991
Getting : 992
The thread Consumer Going ta sleep...
Getting : 993

但您还会看到所有 get 的顺序都是正确的,所有 put 的顺序也是正确的。因此,当涉及多个线程时,这是 Java 中输出工作方式的问题。

关于java - 生产者消费者多线程为什么需要Thread.sleep?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18900763/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com