2

I have a class that extends Thread that downloads files. I want to ensure that only one download is occurring at once, so I have a static reference to the class, and check to see if it is null before creating a new reference. However occasionally I notice that another instance of this class is created, and therefore downloading on a different thread. I'm trying to figure out what could cause this, however, would it be a bad idea in general to mark the run() method of the Thread to synchronized (or the method that calls start()) ? Are there any side effects to be aware of?

4

4 回答 4

1

您需要确保在 JVM 的生命周期中只创建所述对象的单个实例。为此,有一个非常著名的单例模式可以确保这一点。

将构造函数设为私有。提供一个静态工厂方法来创建实例。

例子:

Downloader{

  private static volatile Downloader iDownloader=null; 
  private Downloader(){
  }

 public static Downloader createDownloader(){
     if(iDownloader==null){
     synchronized(Downloader.class){
      if(iDownloader==null)
       iDownloader=new Downloader();
       }
      }
  return iDownloader; 
}

}

于 2013-09-08T21:45:48.937 回答
1

如果您想随时限制运行的下载次数,您应该以这种方式使用信号量机制,您可以扩展下载次数,您不需要以这种方式同步运行,将来如果您需要运行两次下载,您只需增加你的信号量大小

于 2013-09-08T21:40:13.133 回答
0

您可以使用 Android Framework 中的 Looper 类使您的线程成为管道线程,并通过 Handler 实例将您的下载请求排入队列

这是一个很好的教程,可以帮助你 http://mindtherobot.com/blog/159/android-guts-intro-to-loopers-and-handlers/

于 2013-09-08T21:57:55.663 回答
0

是的,您需要同步对静态标志的访问。synchronized用方法来做到这一点很好 。但是,当您完成所有操作后,您将实施一个锁。所以看看 Java Lock 类。启动文件传输的方法需要在启动下载线程之前抢到锁。下载完成或失败后线程释放它。正如文档指出的那样,必须 100% 确定发布,否则所有下载都将被阻止。

于 2013-09-08T21:46:17.500 回答