我是java新手,我想写一个线程库作为练习。它将以这种方式工作,
在主线程中,一些作业(作为字符串)将被添加到作业队列中,当工作线程完成作业时,它会将其添加到已完成队列中。主线程将从完成的队列中获取结果。当所有工作都完成后,主线程会通知工作人员停止。以下是我到目前为止编写的一些代码:
public List<int> get() {
WorkerThread[] threads = new WorkerThread[numThreads];
LinkedList<int> results = new LinkedList<>();
int workCount = 0;
for (int i = 0; i < numThreads; i++) {
threads[i] = new WorkerThread();
threads[i].start();
}
// reader is a BufferedReader
while ((String line = reader.readLine()) != null) {
// put string to job queue
workCount++
}
while(workCount) {
//result = get result from finished queue, and add it to results LinkedList
workCount--;
}
for (int i = 0; i < numThreads; i++) {
threads[i].canStop(); // this sets a private variable that makes infinite while loop to stop
threads[i].join();
}
return results;
}
但是我对为此使用哪种 Queue 实现感到困惑。如文档所示,有 11 种不同的队列实现。