该代码的控制流程如何工作?

时间:2019-06-01 09:35:16

标签: java java-threads

我想了解线程在这里的工作方式。我对执行notifyall()语句时发生的事情感到困惑,执行notifyall()的当前线程会被延迟而另一个线程执行吗?

另外,正在执行wait()的当前线程会延迟执行另一个线程吗?总体而言,我想知道代码在这里是如何工作的。

import java.util.Random;

public class Main {

public static void main(String[] args) {
    Message message = new Message();
    (new Thread(new Writer(message))).start();
    (new Thread(new Reader(message))).start();
}
}

class Message {
private String message;
private boolean empty = true;

public synchronized String read() {
    while (empty) {
        try {
            wait();
        } catch (InterruptedException e) {

        }
    }
    empty = true;
    notifyAll();
    return message;
}

public synchronized void write(String message) {
    while (!empty) {
        try {
            wait();
        } catch (InterruptedException e) {

        }
    }
    empty = false;
    this.message = message;
    notifyAll();
}
}

class Writer implements Runnable {
private Message message;

public Writer(Message message) {
    this.message = message;
}

public void run() {
    String messages[] = {
            "Hello",
            "How are you",
            "Are you doing well",
            "Ok Bye!"
    };

    Random random = new Random();

    for (int i = 0; i < messages.length; i++) {
        this.message.write(messages[i]);
        try {
            Thread.sleep(random.nextInt(2000));
        } catch (InterruptedException e) {

        }
    }
    this.message.write("Finished");
}
}

class Reader implements Runnable {
private Message message;

public Reader(Message message) {
    this.message = message;
}

public void run() {
    Random random = new Random();

    for (String latestMessage = this.message.read(); !latestMessage.equals("Finished");
         latestMessage = this.message.read()) {
        System.out.println(latestMessage);
        try {
            Thread.sleep(random.nextInt(2000));
        } catch (InterruptedException e) {

        }
    }
}
}

0 个答案:

没有答案