synchronized的用法

  1. synchronized的几种用法

    synchronized关键字最主要有以下5种应用方式,下面分别介绍。 1. 修饰对象普通方法,作用于当前对象,进入同步方法前要获得当前对象的锁 2. 修饰对象静态方法,作用于当前类对象加锁,进入同步该方法前要获得当前类对象的锁 3. 修饰代码块,指定加锁对象,对给定对象加锁,进入同步代码库前要获得指定对象的锁。 4. 修饰 this,指定当前对象,对给当前对象加锁,进入同步代码前要获得当前对象的锁(该方式和方式1作用相同)。 5. 修饰 xxx.class,(该方式和方式2作用相同)。
  2. 锁竞争说明

同时调用两个都加有synchronized的方法时存在锁竞争关系(同时调用时会一个先输出,另一个晚两秒输出)以下代码同时调用会产生竞争关系(this的作用相同)

	public synchronized void getSex() throws InterruptedException {
		Thread.sleep(2000);
	    System.out.println("getSex synchronized : " + System.currentTimeMillis());
	}
	
	public synchronized void getHeight() throws InterruptedException {
	    Thread.sleep(2000);
	    System.out.println("getHeight synchronized : " + System.currentTimeMillis());
	}
	
	public void getWeight() throws InterruptedException {
	     synchronized (this){
	          Thread.sleep(2000);
	          System.out.println("getWeight synchronized : " + System.currentTimeMillis());
	     }
	}
  • 同时调用两个都加有synchronized的静态(static)方法时存在锁竞争关系(同时调用时会一个先输出,另一个晚两秒输出)
	public static synchronized void getName() throws InterruptedException {
	     Thread.sleep(2000);
	     System.out.println("getName static synchronized : " + System.currentTimeMillis());
	}
	
	public static synchronized void getAge() throws InterruptedException {
	      Thread.sleep(2000);
	      System.out.println("getAge static synchronized : " + System.currentTimeMillis());
	}
  • 同时调用锁代码块的要看锁的目标是不是同一个,如果是同一个时就存在锁竞争关系,如果不是则没有关系 当传入的参数一样则有竞争关系
	public void getQQ(String qq) throws InterruptedException {
	      synchronized (qq){
	           Thread.sleep(2000);
	           System.out.println("getQQ QQ synchronized : " + System.currentTimeMillis());
	      }
	}
	
	public void getWX(String wx) throws InterruptedException {
	      synchronized (wx){
	           Thread.sleep(2000);
	           System.out.println("getWX WX synchronized : " + System.currentTimeMillis());
	      }
	}

这里要注意点的就是 当传入的是getWX(“55”)和getQQ(“55”),getWX(new String(“55”))和getQQ(new String(“55”))这两中的结果是不同的 注意前面的存在竞争关系,后面不存在,因为new 是从新创建了对象,内存地址不是同一个

  • 同时一个synchronized的静态(static)方法和一个普通synchronized方法时 和一个synchronized代码块时(代码块不是 this和xxx.class),不存在竞争关系
public synchronized void getSex() throws InterruptedException {
       Thread.sleep(2000);
       System.out.println("getSex synchronized : " + System.currentTimeMillis());
}

public static synchronized void getAge() throws InterruptedException {
      Thread.sleep(2000);
      System.out.println("getAge static synchronized : " + System.currentTimeMillis());
}

public void getWX(String wx) throws InterruptedException {
      synchronized (wx){
          Thread.sleep(2000);
          System.out.println("getWX WX synchronized : " + System.currentTimeMillis());
      }
}

这里要注意点的就是 synchronized代码块必须不是this和xxx.class,要不然会有竞争关系 因为this和synchronized普通方法效果相同,xxx.class与synchronized静态方法效果相同

以下是全部代码(有不对的希望大家指正)

/**
 * 文件介绍
 *
 * @author YangLD
 * @date 2018/8/3 21:17
 */
public class RunMain {


    static{
        System.out.println("static");
    }

    public static void main(String[] args) throws IllegalAccessException, InstantiationException {

        RunMain runMain = RunMain.class.newInstance();

        System.out.println(System.currentTimeMillis());
        CyclicBarrier cyclicBarrier = new CyclicBarrier(9);
        ThreadUtil.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    cyclicBarrier.await();
                    RunMain.getName();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        });
        ThreadUtil.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    cyclicBarrier.await();
                    RunMain.getAge();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        });
        ThreadUtil.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    cyclicBarrier.await();
                    runMain.getEmail();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        });
        ThreadUtil.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    cyclicBarrier.await();
                    runMain.getSex();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        });

        ThreadUtil.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    cyclicBarrier.await();
                    runMain.getHeight();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        });
        ThreadUtil.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    cyclicBarrier.await();
                    runMain.getWeight();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        });
        ThreadUtil.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    cyclicBarrier.await();
                    runMain.getQQ("qq");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        });
        ThreadUtil.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    cyclicBarrier.await();
                    runMain.getWX("qq");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        });
        ThreadUtil.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    cyclicBarrier.await();
                    runMain.getAli();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    public static synchronized void getName() throws InterruptedException {
        Thread.sleep(2000);
        System.out.println("getName static synchronized : " + System.currentTimeMillis());
    }

    public static synchronized void getAge() throws InterruptedException {
        Thread.sleep(2000);
        System.out.println("getAge static synchronized : " + System.currentTimeMillis());
    }

    public synchronized void getSex() throws InterruptedException {
        Thread.sleep(2000);
        System.out.println("getSex synchronized : " + System.currentTimeMillis());
    }

    public synchronized void getHeight() throws InterruptedException {
        Thread.sleep(2000);
        System.out.println("getHeight synchronized : " + System.currentTimeMillis());
    }

    public void getEmail() throws InterruptedException {
        Thread.sleep(2000);
        System.out.println("getEmail : " + System.currentTimeMillis());
    }

    public void getWeight() throws InterruptedException {
        synchronized (this){
            Thread.sleep(2000);
            System.out.println("getWeight synchronized : " + System.currentTimeMillis());
        }
    }

    public void getQQ(String qq) throws InterruptedException {
        synchronized (qq){
            Thread.sleep(2000);
            System.out.println("getQQ QQ synchronized : " + System.currentTimeMillis());
        }
    }

    public void getWX(String wx) throws InterruptedException {
        synchronized (wx){
            Thread.sleep(2000);
            System.out.println("getWX WX synchronized : " + System.currentTimeMillis());
        }
    }

    public void getAli() throws InterruptedException {
        synchronized (RunMain.class){
            Thread.sleep(2000);
            System.out.println("getAli synchronized : " + System.currentTimeMillis());
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值