我想实现自己的记录器,将日志写入文件。它可以从多个线程运行,并且问题是如何同步对日志文件的访问。同步访问文件
private synchronized static void writeToFile(String tag, String msg,
Throwable tr, Context ctx) {
try {
String s = System.getProperty("line.separator");
File f = Environment.getExternalStorageDirectory();
Log.i(TAG, "Path to app " + f.getAbsolutePath());
File l = new File(f, "log.txt");
if (!l.exists()) {
l.createNewFile();
}
String e = Log.getStackTraceString(tr);
StringBuilder b = new StringBuilder();
b.append(HttpCommand.getDateForUrl(System.currentTimeMillis()));
b.append(tag);
b.append(msg);
b.append(e);
b.append(s);
OutputStream out = new FileOutputStream(l);
out.write(b.toString().getBytes());
out.flush();
out.close();
} catch (IOException e) {
Log.e(TAG, "Failed to create backup");
}
}
是否足够同步通过类同步访问数据库,如果我通过它在不同的线程?
synchronized(X.class) {
writeTiFile()
}
是的,但如果我删除静态修饰符并在线程中传递多个实例会怎么样? –