java 删除与新增使用synchronized 给出示例
时间: 2023-02-19 18:39:04 浏览: 71
Synchronized 可以用来保证多线程环境下的安全,比如:
public class Test {
public static void main(String[] args) {
Test test = new Test();
// 创建一个锁对象
Object lock = new Object();
// 创建线程1
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock) {
test.delete();
}
}
});
// 创建线程2
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock) {
test.add();
}
}
});
// 启动线程
thread1.start();
thread2.start();
}
public void delete() {
System.out.println("删除操作");
}
public void add() {
System.out.println("新增操作");
}
}
阅读全文