实现进程同步常用的是synchronized,凡是标记为同步的方法或者对账只会在同一时间被一个进程使用。
如果是在进行写入或者更新一类的操作,使用synchronized即可满足同步操作。
如果是读写同步的操作则没必要互斥,可以支持多个进程同时读取。这个就用到ReadWriteLock。加锁方法如下
//写入方法方法
public static synchronized void set(int data) {
rwl.writeLock().lock();// 取到写锁
System.out.println(Thread.currentThread().getName() + "准备写入数据");
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "写入" + data);
}
//读取方法
public static synchronized void get() {
rwl.readLock().lock();
System.out.println(Thread.currentThread().getName() + "准备读取数据");
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "读取" + data);
}