`
hotpro
  • 浏览: 21216 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
文章分类
社区版块
存档分类
最新评论

synchronized 关键字 老生常谈

阅读更多
  • synchronized这个关键字要修饰一段代码。
  • 一个线程(Thread)要运行一段代码,要获得的锁有两种 对象锁和类锁.
  •           对象锁:thread要获得某个具体的对象的的锁,才能运行这段代码.
              类锁:   thread要获得这个类的锁,才能运行这段代码.



下面就按这两种锁来分类

1. 对象锁
a. synchronized 修饰普通方法
   
synchronized void syncMethod() {}

b. synchronized 修饰代码块
    void method(Foo foo) {
        synchronized(foo) {
        }
    }

[注]
    synchronized void syncMethod() {}跟
    void method() {
        synchronized(this) {
        }
    }
    效果是一样的。

2. 类锁
c. synchronized 修饰static方法
  
synchronized void static syncStaticMethod() {}

d. synchronized 修饰代码块
   
class Foo {
        void method() {
            synchronized(Foo.class) {
            }
        }   
    }

[注]c和d的效果是一样的。

Tips:
      i. synchronized关键字放在void之前, public 之后

[补充1]
        看到synchronized修饰runnable 的run方法。

package com.test.testrun;

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

class SyncRun implements Runnable {

    public void run() {
//        synchronized(this) {         //point 1
            for (int i = 0; i < 100; i++) {
                System.out.println(i);
                Thread.yield();
            }
//        }
    }
    
}

public class TestRunMethod {

    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        SyncRun r = new SyncRun();
        for (int i = 0; i < 10; i++) {
//            exec.execute(new SyncRun());    //point 2
            new Thread(r).start();
        }
        
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {

            e.printStackTrace();
        }
        exec.shutdownNow();
    }
}


1. run方法里把synchronized注释掉,运行。
   结果很乱.
2. run方法把里用synchronized修饰,运行。
   结果很整齐.

point 2不知道有什么用!!!
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics