Java/Android:同步 vs 队列实现 [英] Java/Android: Synchronized vs Queue implementation
问题描述
我可以问一个 Java 新手问题吗?
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();
}
我添加了同步",以便下载一个一个.(不能同时进行多次下载).
我猜即使多次调用 download(),synchronized 也会阻塞其他线程,直到第一个线程完成.
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.
上面的代码能用吗?还是我必须实现队列?并一一出队?
同步可以阻止足够"的线程吗?(30?50?)还是有限制?
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?
推荐答案
上面的代码能用吗?
是的,只要object
在所有线程中都指向同一个对象,synchronized块中的代码一次只会被一个线程执行.
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.
[...] 还是我必须实现队列?并一一出队?
一般来说,我建议您尽可能使用高级构造(例如来自 java.util.concurrent 包).例如,您可以考虑为这些类型的事情使用执行程序服务.
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.
[...] 同步可以阻塞足够多"的线程吗?(30?50?)还是有限制?
不,没有限制.至少不会接近 30 或 50 :-)
No, no limits. At least not near 30 or 50 :-)
这篇关于Java/Android:同步 vs 队列实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!