举例
import lombok.extern.slf4j.Slf4j; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @Slf4j public class SynchronizedExample2 { // 修饰一个类 public static void test1(int j) { synchronized (SynchronizedExample2.class) { for (int i = 0; i < 3; i++) { log.info("test1 {} - {}", j, i); } } } // 修饰一个静态方法 public static synchronized void test2(int j) { for (int i = 0; i < 3; i++) { log.info("test2 {} - {}", j, i); } } public static void main(String[] args) { SynchronizedExample2 example1 = new SynchronizedExample2(); SynchronizedExample2 example2 = new SynchronizedExample2(); ExecutorService executorService = Executors.newCachedThreadPool(); executorService.execute(new Runnable() { @Override public void run() { example1.test1(1); System.out.println(Thread.currentThread().getName()+":使用正常方式创建线程"); } }); executorService.execute(() -> { example2.test1(2); System.out.println(Thread.currentThread().getName()+":使用lambda表达式创建线程"); }); } }
输出
14:44:09.488 [pool-1-thread-1] INFO com.mmall.demo.example.sync.SynchronizedExample2 - test1 1 - 0 14:44:09.493 [pool-1-thread-1] INFO com.mmall.demo.example.sync.SynchronizedExample2 - test1 1 - 1 14:44:09.493 [pool-1-thread-1] INFO com.mmall.demo.example.sync.SynchronizedExample2 - test1 1 - 2 pool-1-thread-1:使用正常方式创建线程 14:44:09.594 [pool-1-thread-1] INFO com.mmall.demo.example.sync.SynchronizedExample2 - test1 2 - 0 14:44:09.594 [pool-1-thread-1] INFO com.mmall.demo.example.sync.SynchronizedExample2 - test1 2 - 1 14:44:09.594 [pool-1-thread-1] INFO com.mmall.demo.example.sync.SynchronizedExample2 - test1 2 - 2 pool-1-thread-1:使用lambda表达式创建线程