在两个线程之间进行通信 [英] Communicating between two threads

查看:93
本文介绍了在两个线程之间进行通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个帖子, A 有一个列表。 List包含一些对象。现在我想设计一个机制,通过该机制,我可以向线程发送一些消息 A

I have a thread, A which has a list. List holds some objects. Now I want to design a mechanisim by which I can send some message to thread A.

线程A 在循环中运行(它不等待或休眠)。
其他一些线程, B ,向线程 A 和线程发送一些消息A 清空所有队列。

Thread A runs in a loop (it does not wait or sleep). Some other thread, B, sends some message to thread A and thread A empties all its queues.

如何在线程之间发送消息?

How can I send messages between threads?

class A extends Thread {
    List<Object> objs = something; //Init it
    void run() {
        while(true) {
            //Body which works on objects.
            //After receiving an external message, "A" should perform some action, for example, empty objects.
        }
    }
}

编辑:
我可以这样做吗?

Can I do it like this?

class A extends Thread {
    List<Object> objs = something; //Init it
    Boolean flag = false;

    public void setFlag(boolean value) {
        synchronized(flag) {
            this.flag = value;
        }
    }

    public void getFlag() {
        synchronized(flag) {
            return this.flag;
        }
    }

    void run() {
        while(true) {
            //Body which works on objects.
            //After receiving an external message, A should perform some action, for example, empty objects.
            if (getFlag == true)
                //Empty list
        }
    }
}


推荐答案

你可以有一个 BlockingQueue 。其他线程会将消息放入队列。作为 while(true)循环的一部分,线程 A 民意调查 队列并处理已到达的任何消息。

You could have a BlockingQueue of message objects. Other threads would place messages onto the queue. As part of the while(true) loop, thread A would poll the queue and process any messages that have arrived.

代码:

class A extends Thread{
 List<Object>  objs = something ;//init it
 BlockingQueue<Message> queue = new LinkedBlockingQueue<Message>();
 void run(){
     while(true){
       Message msg;
       while ((msg = queue.poll()) != null) {
         // process msg
       }
       // do other stuff
     }
   }
}

其他线程现在可以调用 queue.put ()将消息发送到线程 A

Other threads can now call queue.put() to send messages to thread A.

这篇关于在两个线程之间进行通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆