我有一个线程,A
其中有一个列表。列表保存一些对象。现在我想设计一种机制,通过它我可以向线程发送一些消息A
.
Thread A
循环运行(它不等待或睡眠)。
其他一些线程,B
,向线程发送一些消息A
和线程A
清空其所有队列。
如何在线程之间发送消息?
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.
}
}
}
编辑:
我可以这样做吗?
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 http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/BlockingQueue.html消息对象。其他线程会将消息放入队列中。作为while(true)
循环、线程A
would poll http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/LinkedBlockingQueue.html#poll()队列并处理所有到达的消息。
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
}
}
}
其他线程现在可以调用queue.put()
向线程发送消息A
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)