高并发读写导致ConcurrentModificationException异常的解决办法

时间:2024-04-06 15:38:37

1、使用java.util.concurrent包下面的并发容器

     网上搜、查API文档。


2、读写分离,写操作加锁(synchronized为例,其中synchronized锁住的是括号里的对象

Thread thread = new Thread(new Runnable() {
    public void run() {
        for (int i = 0; i < 3; i++) {
            SyncManager.getInstance().operate1();
        }
    }
});
thread.start();

Thread thread2 = new Thread(new Runnable() {
    public void run() {
        for (int i = 0; i < 3; i++) {
            SyncManager.getInstance().operate2();
        }
    }
});
thread2.start();
public class SyncManager {

    private Object mLockObj = new Object();

    private static SyncManager sInstance;

    public static SyncManager getInstance() {
        if (sInstance == null) {
            sInstance = new SyncManager();
        }
        return sInstance;
    }

    public void operate1() {
        synchronized (mLockObj) {
            Log.e("concurrent", "operate1 开始..");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.e("concurrent", "operate1 结束..");
        }
    }

    public void operate2() {
        synchronized (mLockObj) {
            Log.e("concurrent", "operate2 开始..");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.e("concurrent", "operate2 结束..");
        }
    }
}
高并发读写导致ConcurrentModificationException异常的解决办法


3、读写分离,写操作使用newSingleThreadExecutor异步(创建一个单线程的线程池,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行,若线程出现异常将会有一个新的线程来替代)

public class SyncManager {

    private ExecutorService mExecutorService = Executors.newSingleThreadExecutor();

    private static SyncManager sInstance;

    public static SyncManager getInstance() {
        if (sInstance == null) {
            sInstance = new SyncManager();
        }
        return sInstance;
    }

    public void operate1() {
        mExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                Log.e("concurrent", "operate1 开始..");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Log.e("concurrent", "operate1 结束..");
            }
        });
    }

    public void operate2() {
        mExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                Log.e("concurrent", "operate2 开始..");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Log.e("concurrent", "operate2 结束..");
            }
        });
    }
}

高并发读写导致ConcurrentModificationException异常的解决办法