synchronized
依赖 JVM
针对对象的锁
锁分类: 1.对象锁 2.类锁
同步代码块、同步静态方法、同步实例方法、同步类
代码示例
package com.jysemel.java.lock;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SynchronizedExample {
public static void main(String[] args) {
SynchronizedExample example = new SynchronizedExample();
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(example::test);
executorService.execute(example::test);
executorService.execute(SynchronizedExample::test3);
executorService.execute(SynchronizedExample::test3);
}
//修饰代码块
public void test () {
synchronized (this) {
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
}
}
//修饰方法
public synchronized void test2 () {
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
}
//修饰静态方法
public static synchronized void test3 () {
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
}
//修饰一个类
public static class SynchronizedClass {
public static void test4 () {
synchronized (SynchronizedClass.class) {
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
}
}
}
}
