-2

我已经创建了三个类,我使用其中一个来为另外两个类创建和启动两个单独的线程。如何在这两个类中传递值?

4

1 回答 1

2

我建议使用包中的LinkedTransferQueuejava.util.concurrent。每个线程都有一个队列,该队列将用作来自其他线程的消息的收件箱take(),并且可以将来自它的消息进行操作,并将transfer()消息发送到其他线程的邮箱。

import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.TransferQueue;

class Leader implements Runnable {
    private final Follower follower;
    private final TransferQueue<String> queue = new LinkedTransferQueue<>();

    public Leader(Follower follower) {
        this.follower = follower;
    }

    public void sendMessage(String message) throws InterruptedException {
        queue.transfer(message);
    }

    public void run() {
        try {
            follower.sendMessage("WAKE UP, SLEEPYHEAD!");
            while (true) {
                String message = queue.take();
                if (message.equals("STOP")) {
                    break;
                } else {
                    follower.sendMessage("SAY " + message);
                }
            }
            System.out.println("Exiting");
        } catch (Exception e) {
            // we're exiting anyway, let it go
        }
    }
}

class Follower implements Runnable {
    private final TransferQueue<String> queue = new LinkedTransferQueue<>();

    public void sendMessage(String message) throws InterruptedException {
        queue.transfer(message);
    }

    public void run() {
        try {
            while (true) {
                String message = queue.take();
                if (message.equals("STOP")) {
                    break;
                } else if (message.startsWith("SAY ")) {
                    System.out.println(message.substring(4));
                } else {
                    System.out.println("My leader gave me a message I don't understand.");
                }
            }
            System.out.println("I've been told to stop.");
        } catch (Exception e) {
            // we're exiting anyway, let it go
        }
    }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Follower follower = new Follower();
        Leader leader = new Leader(follower);
        Thread one = new Thread(leader);
        Thread two = new Thread(follower);
        // start the follower first
        two.start();
        one.start();

        // tell the leader, and the leader will tell the follower
        leader.sendMessage("Hello, world");
        leader.sendMessage("Good-bye");

        leader.sendMessage("STOP");
        follower.sendMessage("STOP");
        one.join();
        two.join();
        System.out.println("Be seeing you.");
    }
}

如果您不希望执行传输的线程等到收到消息后再继续执行,则可以使用 aLinkedBlockingQueue代替,但是当线程彼此领先并且消息被认为是“超出命令。” 但是,对于真正的异步代码,这可能正是您想要的。

在这个例子中,我坚持使用更直观的 TransferQueue。

于 2018-04-18T06:10:44.257 回答