我认为我做错了。我正在创建线程,以便从共享队列中剔除一些数据。我的问题是程序速度慢,内存不足,我怀疑队列可能不像我希望的那样共享。我怀疑这是因为在我的代码中,我添加了一行显示队列的大小,如果我启动2个线程,然后我得到两个完全不同数字的输出,似乎自己增加(我认为它可能是相同的数字,但也许它从100跳到2,等等,但看完它后显示105和5,并以不同的速率运行,如果我有4个线程,那么我看到4个不同的数字)。如何实现一个可以被多个线程处理的队列?
这是相关部分的片段。我在节目
static class queue_class {
int number;
int[] data;
Context(int number, int[] data) {
this.number = number;
this.data = data;
}
}
然后我将一些职位的调用后创建队列的顶部创建队列我想要的数据静态类..
static class process_threaded implements Callable<Void> {
// queue with contexts to process
private Queue<queue_class> queue;
process_threaded(queue_class request) {
queue = new ArrayDeque<queue_class>();
queue.add(request);
}
public Void call() {
while(!queue.isEmpty()) {
System.out.println("in contexts queue with a size of " + queue.size());
Context current = contexts.poll();
//get work and process it, if it work great then the solution goes elsewhere
//otherwise, depending on the data, its either discarded or parts of it is added back to queue
queue.add(new queue_class(k, data_list));
,你可以看到,数据有3个选项,如果数据是好的,就会被发送出去,如果数据完全可怕或丢回队列就丢弃。我认为队列正在发送,但我怀疑是因为每个线程都在自己的队列中工作,而不是共享队列。
这是猜测正确的,我在做这错了吗?
此代码不会编译。你是否尝试编译和执行某些东西,然后问一个具体的问题,而不是编写一个不被java编译器接受的伪代码? – 2012-04-14 04:24:19
我的实际代码编译..我没有想到任何人都想编译它,所以我拿了代码,清理了与问题无关的信息,只是为了展示我在做什么。我不需要代码只是逻辑,并认为上面的代码应该让我知道我在做什么。 – 2012-04-14 04:33:28
您应该阅读[实践中的Java并发](http://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601)以编写线程安全代码的专业知识。 – 2012-04-14 04:54:35