Android 多线程保证操作同步(同步锁的俩种)
2021-11-02 本文已影响0人
皓皓amous
synchronized这个关键字可以直接加到方法上也可使用synchronized代码块,将需要同步的代码放到这个代码块中,如:
private synchronized void writeLog() {
for (int i = 0; i < 3; i++) {
try {
Log.e(TAG, "showLog: " + Thread.currentThread().getName() + "写入中");
Thread.sleep(new Random().nextInt(1000));
Log.e(TAG, "showLog: " + Thread.currentThread().getName() + "写入完成");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void readLog() {
synchronized (this) {
for (int i = 0; i < 3; i++) {
try {
Log.e(TAG, "showLog: " + Thread.currentThread().getName() + "读取中");
Thread.sleep(new Random().nextInt(1000));
Log.e(TAG, "showLog: " + Thread.currentThread().getName() + "读取完成");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}