synchronized一个Object对象是为了什么?

中才德创 2014-05-22 03:16:05
public class RecycleViewList {
static final String TAG = "RecycleViewList";

private static final int INI_LIST_SIZE = 2;
private final SparseArray<SoftReference<View>> mViewCache = new SparseArray<SoftReference<View>>(INI_LIST_SIZE);

private Object syncLock = new Object();

public void addToCache(int idx, View v) {
synchronized (syncLock) {
int size = mViewCache.size();
Log.d(TAG, "addToCache: index="+idx+", size = "+size+", view="+v);
mViewCache.put(idx, new SoftReference<View>(v));
}
}

public View fetchCacheView(int idx) {
synchronized (syncLock) {
int size = mViewCache.size();
Log.d(TAG, "fetchCacheView: size = "+size);
if ((idx>=size) || (idx<0)) {
return null;
}

Log.d(TAG, "fetchCacheView: mViewCache.size() = "+mViewCache.size());
SoftReference<View> cachedView = mViewCache.get(idx);
Log.d(TAG, "fetchCacheView: cachedView= "+cachedView);

if (cachedView != null) {
View v = cachedView.get();
Log.d(TAG, "fetchCacheView: cachedView.get()= "+v);
if (v != null) {
Log.d(TAG, "fetchCacheView: leave with="+v);
return v;
}
}
}
return null;
}

public void clearCacheView() {
synchronized (syncLock) {
int size = mViewCache.size();
Log.d(TAG, "clearCacheView: size = "+size);
mViewCache.clear();
}
}

public int getSize() {
synchronized (syncLock) {
int size = mViewCache.size();
Log.d(TAG, "getSize: size = "+size);
return size;
}
}
}
...全文
147 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhujunhua2012 2014-05-23
  • 打赏
  • 举报
回复
静态函数,那就是应该用类级别的锁了,synchronized (FManager.class);或者在类里面用一个static的变量(private static Object syncObj = new Object();),然后synchronized(syncObj)即可。
中才德创 2014-05-23
  • 打赏
  • 举报
回复
可是在静态类函数里,实现synchronized(this) {}却不行,报Cannot use this in a static context。 原因是因为,静态类函数隶属类,它没有this。这该如何呢?
public class FManager {
    /*
     * 函数介绍:保存log到日志文件
     * 输入参数:strLog字符串
     * 输出参数:无
     * 返回值  :无
     */
	public static void saveLogSD(String strLog) {
		Log.v(TAG, "saveLogSD enter");
媒体盒子 2014-05-22
  • 打赏
  • 举报
回复
用于多线程间的同步,当一个线程调用方法进入 synchronized (syncLock) { int size = mViewCache.size(); Log.d(TAG, "addToCache: index="+idx+", size = "+size+", view="+v); mViewCache.put(idx, new SoftReference<View>(v)); } 后其他线程调用该方法或去他含synchronized (syncLock) {的方法都必须wait 到 synchronized (syncLock) {}里面的代码执行完

80,351

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧