Communicating between two threads

不打扰是莪最后的温柔 提交于 2019-11-26 16:27:09

问题


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.

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.
        }
    }
}

EDIT: 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
        }
    }
}

回答1:


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.

In code:

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
     }
   }
}

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




回答2:


In a simplistic case you can add some instance variable to thread A class and have thread B set its value to indicate that thread A must clear its' queues. In more advanced case you can use some queue of messages that both threads A and B can access. B would place a message there and A would read and act on it.

In all cases, access to variable or queue must be properly guarded for multiple threads access.




回答3:


You should be able to add a method to class "A" that can be called elsewhere in your code. Just keep the reference to your instance of class "A" in an accessible place.

class A extends Thread{
 List<Object>  objs = something ;//init it
 void run(){
   while(true){
       //body which works on objs
       //open receiving external message A should perform some action ie empty objs
     }
   }
  void ChangeState()
  {
     //clear objs
  } 
}


来源:https://stackoverflow.com/questions/6916398/communicating-between-two-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!