使用线程时传输值

时间:2018-04-18 05:42:12

标签: java multithreading java-threads spawning

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

1 个答案:

答案 0 :(得分:2)

我建议使用java.util.concurrent包中的LinkedTransferQueue。每个线程都有一个队列,可以作为来自其他线程的消息的收件箱,并且可以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.");
    }
}

如果您不希望执行传输的线程等到收到消息之前等待,那么您可以使用LinkedBlockingQueue代替,但是当线程先于其他消息和消息时,这可能会令人惊讶被认为是“乱序”。但是,在真正异步代码的情况下,这可能正是您想要的。

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