---
title: "synchronized 关键字 老生常谈"
author: "hotpro"
date: "2010-08-27T09:51:13Z"
tags: []
categories: ["编程语言"]
slug: "synchronized"
draft: false
lastmod: "2010-08-27T10:08:47Z"
id: 748438
url: "https://hotpro.iteye.com/blog/748438"
---

synchronized这个关键字要修饰一段代码。
一个线程(Thread)要运行一段代码，要获得的锁有两种 对象锁和类锁. 
          对象锁：thread要获得某个具体的对象的的锁，才能运行这段代码. 
          类锁：   thread要获得这个类的锁，才能运行这段代码.



下面就按这两种锁来分类

**1. 对象锁**
a. synchronized 修饰普通方法
    
```java
synchronized void syncMethod() {}
```

b. synchronized 修饰代码块

```java
    void method(Foo foo) {
        synchronized(foo) {
        }
    }
```


    synchronized void syncMethod() {}跟
    void method() {
        synchronized(this) {
        }
    }
    效果是一样的。

**2. 类锁**
c. synchronized 修饰static方法
   
```java
synchronized void static syncStaticMethod() {}
```

d. synchronized 修饰代码块
    
```java
class Foo {
        void method() {
            synchronized(Foo.class) {
            }
        }   
    }
```

c和d的效果是一样的。

Tips:
      i. synchronized关键字放在void之前, public 之后

**<span style="color:red"></span>**
        看到synchronized修饰runnable 的run方法。


```java
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不知道有什么用！！！