Synchronize 作用于方法和静态方法区别
测试代码如下所示
- private void test() {
- final TestSynchronized test1 = new TestSynchronized();
- final TestSynchronized test2 = new TestSynchronized();
- Thread t1 = new Thread(new Runnable() {
- @Override
- public void run() {
- test1.method01("a");
- //test1.method02("a");
- }
- });
- Thread t2 = new Thread(new Runnable() {
- @Override
- public void run() {
- test2.method01("b");
- //test2.method02("a");
- }
- });
- t1.start();
- t2.start();
- }
- private static class TestSynchronized{
- private int num1;
- public synchronized void method01(String arg) {
- try {
- if("a".equals(arg)){
- num1 = 100;
- System.out.println("tag a set number over");
- Thread.sleep(1000);
- }else{
- num1 = 200;
- System.out.println("tag b set number over");
- }
- System.out.println("tag ="+ arg + ";num ="+ num1);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- private static int num2;
- public static synchronized void method02(String arg) {
- try {
- if("a".equals(arg)){
- num2 = 100;
- System.out.println("tag a set number over");
- Thread.sleep(1000);
- }else{
- num2 = 200;
- System.out.println("tag b set number over");
- }
- System.out.println("tag ="+ arg + ";num ="+ num2);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- // 调用 method01 方法打印日志 [普通方法]
- tag a set number over
- tag b set number over
- tag = b;num =200
- tag = a;num =100
- // 调用 method02 方法打印日志 [static 静态方法]
- tag a set number over
- tag = a;num =100
- tag b set number over
- tag = b;num =200
- 在 static 方法前加 synchronized: 静态方法属于类方法, 它属于这个类, 获取到的锁, 是属于类的锁.
- 在普通方法前加 synchronized: 非 static 方法获取到的锁, 是属于当前对象的锁. [技术博客大总结](https://github.com/yangchong211/YCBlogs)
- 结论: 类锁和对象锁不同, synchronized 修饰不加 static 的方法, 锁是加在单个对象上, 不同的对象没有竞争关系; 修饰加了 static 的方法, 锁是加载类上, 这个类所有的对象竞争一把锁.
来源: http://www.bubuko.com/infodetail-2896452.html