Synchronized修饰的四种情况
标签:Java并发

Synchronized修饰的四种情况

测试修饰代码块和修饰方法:

package com.liuyao.concurrency.example.sync;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created By liuyao on 2018/4/12 20:24.
 */
@Slf4j
public class SynchronizedExample1 {
//    修饰一个代码块
    public void test1(int j){
        synchronized (this){
            for (int i = 0; i < 5; i++) {
                log.info("test1 {}-{}",j,i);
            }
        }
    }
//修饰一个方法
    public synchronized void test2(int j){
        for (int i = 0; i < 5; i++) {
            log.info("test2 {}-{}",j,i);
        }
    }

    public static void main(String[] args) {
        SynchronizedExample1 example1=new SynchronizedExample1();
        ExecutorService executorService=Executors.newCachedThreadPool();
        executorService.execute(()->{
            example1.test1(1);
        });

        executorService.execute(()->{
            example1.test1(2);
        });
    }
}

测试修饰类和静态方法:

package com.liuyao.concurrency.example.sync;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created By liuyao on 2018/4/12 20:24.
 */
@Slf4j
public class SynchronizedExample1 {
//    修饰一个代码块
    public void test1(int j){
        synchronized (SynchronizedExample1.class){
            for (int i = 0; i < 5; i++) {
                log.info("test1 {}-{}",j,i);
            }
        }
    }
//修饰一个方法
    public static synchronized void test2(int j){
        for (int i = 0; i < 5; i++) {
            log.info("test2 {}-{}",j,i);
        }
    }

    public static void main(String[] args) {
        SynchronizedExample1 example1=new SynchronizedExample1();
        SynchronizedExample1 example2=new SynchronizedExample1();
        ExecutorService executorService=Executors.newCachedThreadPool();
        executorService.execute(()->{
            example1.test2(1);
        });

        executorService.execute(()->{
            example2.test2(2);
        });
    }
}

修饰代码块和修饰方法是等价的,而修饰类和修饰静态方法是等价的

子类继承了父类的Synchronized方法,该方法是不带关键字Synchronized的,需要自己再显示声明一下

  • 2 min read

CONTRIBUTORS


  • 2 min read