Java/Android: Synchronized vs Queue implementation

不想你离开。 提交于 2019-12-11 03:58:47

问题


Can I ask a rookie Java question?

I am downloading some files from the web. This method download(url location) is called multiple times.

public static void download(final String url) {
    Thread t = new Thread("download") {
        @Override
        public void run() {
            try {
                synchronized (object) {
                    // download & save
                }
            } catch(Exception e) {}
        }
    };
    t.start();
}

I added "synchronized" so that downloads happens one-by-one. (not multiple downloads occur at the same time).
I am guessing even though download() is called multiple times, synchronized will block other threads until the first thread is finished.

Will above code work? or do I have to implement Queue? and dequeue one-by-one?
Can synchronized block "enough" threads? (30? 50?) or does it have limits?


回答1:


Will above code work?

Yes, as long as object refers to the same object in all threads, the code in the synchronized block will only be executed by one thread at a time.

[...] or do I have to implement Queue? and dequeue one-by-one?

Generally speaking I would recommend you to use as high-level constructs as possible (for instance from the java.util.concurrent package). You may for instance consider using an executor service for these types of things.

[...] Can synchronized block "enough" threads? (30? 50?) or does it have limits?

No, no limits. At least not near 30 or 50 :-)




回答2:


Here's how to do it:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class QueueDownloader {
    private final ExecutorService executor = Executors.newSingleThreadExecutor();
    public void download(final String url) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                // download & save
            }
        });
    }
}

This will queue all runnables (i.e. downloads) on a single background-thread.




回答3:


If you can avoid creating additional threads, you should generally do so. As I understood it, you never want two work items (downloads) in parallel, so the best idea, performance-wise, is using a concurrent queue implementation that is polled by a single worker thread.



来源:https://stackoverflow.com/questions/11619641/java-android-synchronized-vs-queue-implementation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!