

老马说编程
synchronized
可以修饰
1.实例方法
2.static方法
3.代码块
synchronized 实例方法
锁的是this ,就是对象本身,就是说 有线程在调用这个实例的incr方法,其他线程不能同时调用incr和getCount方法
public class Counter {
private int count;
public synchronized void incr(){
count ++;
}
public synchronized int getCount() {
return count;
}
}
synchronized 静态方法
这样锁的是类对象,就是StaticCounter.class
public class StaticCounter {
private static int count = 0;
public static synchronized void incr() {
count++;
}
public static synchronized int getCount() {
return count;
}
}
代码块
可以保护任意对象 ,显示指定
synchronized(随便什么对象,Counter3 .class可以,this也可以)
public class Counter3 {
private int count;
private Object lock = new Object();
public void incr(){
synchronized(lock){
count ++;
}
}
public int getCount() {
synchronized(lock){
return count;
}
}
}
例子 锁this
@Slf4j
public class SynchronizedExample1 {
// 修饰一个代码块
public void test1(int j) {
synchronized (this) {
for (int i = 0; i < 10; i++) {
log.info("test1 {} - {}", j, i);
}
}
}
// 修饰一个方法
public synchronized void test2(int j) {
for (int i = 0; i < 10; i++) {
log.info("test2 {} - {}", j, i);
}
}
public static void main(String[] args) {
//不同的实例 执行不会被锁 因为只锁this
SynchronizedExample1 example1 = new SynchronizedExample1();
SynchronizedExample1 example2 = new SynchronizedExample1();
//线程池
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(() -> {
// example1.test1(1);
example1.test2(1);
});
// executorService.execute不会等上一个 executorService.execute执行完毕
executorService.execute(() -> {
// example2.test1(2);
example2.test2(2);
});
//输出结果表明二个线程交替
}
}