我有一个包含许多文件的文件夹结构,其中一些文件是文本,html,照片,我想遍历主线程中的文件,并且每当该文件是照片时,我都希望将其绘制或)在另一个工作线程上。

  • 每当文件是for循环中的照片时,这似乎都会启动一个新线程?有没有一种方法可以启动该线程一次,并且当它是照片时仅将其传递给文件名?
  • 另一个问题,可以说我在线程1中有一个arrayList对象,我想在线程2中填充它,并在线程1中从中删除对象,我知道它需要同步,我尝试了该示例,但是arraylist似乎在线程2中填充线程1后,该线程为空。我缺少什么?

  • 伪代码:

    线程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()

    10-07 19:01
    查看更多