user1529412
user1529412

Reputation: 3756

Spawning a thread in Java

I have a folder structure with many files, some of these files are text, html, photos, I would like to iterate through the files in main thread, and everytime the file is a photo, I would like to have it drawn or (something) on another worker thread.

Pseudo code:

Thread 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);
    }

Thread 2 Class:

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
    }
}

Upvotes: 2

Views: 1141

Answers (1)

Gray
Gray

Reputation: 116858

This seems to launch a new thread each time a file is a photo in the for loop? Is there a way I can launch the thread once, and just pass it the file name when it is a photo?

I'd use an ExecutorService instead of launching threads directly. Then you can have a single thread handling the thread-pool and you submit as many files as you want to the thread-pool. See the 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();

Let's say I have an arrayList objectin thread 1, I would like to fill it up in Thread 2, and remove objects from it in Thread 1, I know it needs to be synchronized, I tried the example but the arraylist seems to be empty in thread 1 after I filled it in thread 2, What am I missing?

Completely different question which is harder to answer without the specific code. You need to make sure that you are synchronizing both around the updates and the reading of the list. You might want to consider switching to using a BlockingQueue which takes care of the locking for you. You then can have one thread add(...) to the queue and the other one calls take().

Upvotes: 4

Related Questions