我有一个包含许多文件的文件夹结构,其中一些文件是文本,html,照片,我想遍历主线程中的文件,并且每当该文件是照片时,我都希望将其绘制或)在另一个工作线程上。
伪代码:
线程1:
Class Main{
List list = new ArrayList();
void main(){
for(file f : files) {
if(file is PHOTO_TYPE)
new Thread(new ImageRunnable(file)).start();
}
}
//This causes exception because list.size is still empty
for(int i=0; i<10,i++)
list.remove(i);
}
线程2类:
class ImageRunnable extends Main implements Runnable() {
File file;
ImageRunnable(File f){
this.file = f;
}
void run(){
drawPhoto(file);
}
void drawPhoto(File f){
for(int i=0; i<100,i++)
list.add(i);
//something that can take long time
}
}
最佳答案
我会使用ExecutorService
而不是直接启动线程。然后,您可以只有一个线程来处理线程池,并向线程池提交任意数量的文件。参见java tutorial。
// this starts a thread-pool with 1 thread
ExecutorService threadPool = Executors.newFixedThreadPool(1);
for (File f : files) {
// you can submit many files but only 1 thread will process them
threadPool.submit(new ImageRunnable(file));
}
// once we have submitted all jobs to the thread pool, it should be shutdown
threadPool.shutdown();
完全不同的问题,没有特定的代码将很难回答。您需要确保同时同步更新和读取列表。您可能要考虑切换到使用
BlockingQueue
来解决锁定问题。然后,您可以使一个线程add(...)
进入队列,而另一个线程调用take()
。