[英]Blocking queue+Thread+Sequence of execution of threads
我有一个由我的线程对象组成的阻塞队列。 对我来说,这些线程的形成顺序很重要。 每个线程也与一个键相关联。 所以我想做的是,如果某个键的线程正在运行,则该键上的所有其他线程都应被阻止。 但是,当线程完成执行时,应通知并执行队列中具有相同键但最旧的线程。 所以我打算制作一个哈希表阻塞队列,其中哈希表中的键是键,值是线程对象。 我的问题是1.如何搜索与队列中特定键相关的线程。 2.如何通知该线程立即执行。
这就是我在说的。 这应该给您足够的线索。 这未经测试,并且不会根据使用情况照顾您可能需要的同步。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
// E - Element of type key.
public class Design1<E> {
private BlockingQueue<List<MyThread<E>>> myQueue;
// Provides a quicker lookup for the threads for a certain key instead of checking all elements in Queue.
private Map<E, List<MyThread<E>>> myKeyMap;
public Design1() {
// Initialize both myQueue and myKeyMap here.
myQueue = new ArrayBlockingQueue<>(100);
myKeyMap = new HashMap<>();
}
class MyThread<K> extends Thread {
K key;
public K getKey() {
return key;
}
public void run() {
// Process the key
}
}
public void addToQueue(E key) {
List<MyThread<E>> keyThreads = myKeyMap.get(key);
if (keyThreads == null) {
keyThreads = new ArrayList<>();
}
// Create new thread for this key
MyThread<E> t = new MyThread<E>();
keyThreads.add(t);
myKeyMap.put(key, keyThreads);
try {
// Block if full.
myQueue.put(keyThreads);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void processQueue(E key) {
try {
while (true) {
// Fetch elems from Queue - block if empty
List<MyThread<E>> keyThreads = myQueue.take();
E myKey = null;
while (keyThreads.size() > 0) {
// Process all the threads for the same key
MyThread<E> thread = keyThreads.remove(0);
myKey = thread.getKey();
thread.start();
}
if (myKey != null) {
// Clean up hashmap entry too.
myKeyMap.remove(myKey);
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.