开发者

Java: how to store multiple threads that handle different files

I have a server, that sends different files (each opening a thread) on request. each thread doesn't know which file hes handling on creation but only once a message with its name is received, so at that time I need to associate it with the file somehow.

I need the option to wait for all the threads of a certain file to end, and of course all the threads in the server.

The whole threads 开发者_开发知识库thing is done with a thread group, as for the files, I wanted to add a list of threads to each file (I have a wrapper class for it already), and add the option to wait for a certain file. but I don't think this is a good solution, plus I need to use some concurrent collection, and I cant find anything that is just a concurrent linked list.

Any suggestion how to implement this?


I need the option to wait for all the threads of a certain file to end

I did not understand your requirement clearly, but I think something like this will work for you:

// FileSender is the wrapper class you mentioned - where you keep track
// of file->threads association
public class FileSender {
    private final File file;

    private List<Thread> threads = new ArrayList<Thread>();

    public FileSender(File file) {
        this.file = file;
    }

    public void addThread(Thread thread) {
        if (thread != null) {
            this.threads.add(thread);
        }
        for (Iterator<Thread> itr = threads.listIterator(); itr.hasNext();) {
            Thread t = itr.next();
            if (! t.isAlive()) {
                itr.remove();
            }
        }
    }

    // this method blocks until all threads associated with
    // this file has completed execution
    public void waitForCompletion() throws InterruptedException {

        for (Iterator<Thread> itr = threads.listIterator(); itr.hasNext();) {
            Thread thread = itr.next();
            thread.join();
            itr.remove();
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜