使类线程安全



生成此代码是为了在我的应用程序中保存事件历史记录,因为我需要提供一些代码:

public class LogDataBase {
    public LogDataBase(Context context) {
        try {
            this.context = context;
            String logPath = context.getFilesDir() + logStoragePath;
            file = new File(logPath);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
        Errors += ("n" + e.getMessage());
        }
    } 
    public void addItem(String log) {
        try {
            dbWriter = new FileWriter(file, true);
            //appand String log to file
            ....
    }
   public ArrayList<String> getArrayList() { 
     //get all Logs as arraylist
    }
}   

主要问题是如何开发线程安全的应用程序?由于应用程序可能使用服务和多处理,因此多线程应确保代码和类是安全的。

请为这个重要话题提供一些全面的解释(不仅说Synchronization , Lock,...
希望对他人
有用提前谢谢。

同步是保证部分代码是线程安全的最简单方法之一。但是由于它造成的阻塞,它会减慢您的应用程序速度。所以我建议的最好方法是使用生产者消费者实现。因此,步骤如下

  • 制作人
  • 将要记录的项目添加到队列中。应同步添加到队列
  • 然后通知该队列上的所有线程块。
  • 消费者
  • 一个单独的线程,当数据可用时消耗队列。读取队列是唯一需要同步的东西。
  • 如果队列中没有要处理的项目,请等待,直到有人通知

通过这种方式,您可以最大限度地减少阻塞并保证线程安全的方式来处理某些任务。

最新更新