---
title: "synchronized的作用（三）"
author: "wing929"
date: "2008-05-06T22:32:34Z"
tags: ["Java", "thread"]
slug: "synchronized"
draft: false
lastmod: "2008-05-06T22:32:34Z"
id: 190402
url: "https://wing929.iteye.com/blog/190402"
---

b、锁定一个对象或方法，它是静态的
这样锁定，它锁定的是对象所属的类

```java
public synchronized    static void execute(){
      //...
}
```


等同于


```java
public class TestThread {
    public static void execute(){
        synchronized(TestThread.class){
            //
          }
      }
}
```

测试：

目标类：


```java
public class TestThread {
    private static Object lock=new Object();
    public synchronized static void execute(){  //同步静态方法
        for(int i=0;i<100;i++){
              System.out.println(i);
          }    
      }
    public static void execute1(){
        for(int i=0;i<100;i++){
              System.out.println(i);
          }    
      }
    public void test(){
          execute();     //输出是有序的，说明是同步的
        //execute1();  //输出是无须的，说明是异步的
      }
}
```


线程类：调用不同的方法，于是建立了两个线程类



```java
public class ThreadA implements Runnable{
    public void run() {
          TestThread.execute();//调用同步静态方法
      }
}
public class ThreadB implements Runnable{
    public void run() {
          TestThread test=new TestThread();
          test.test();//调用非同步非静态方法
      }
}
```

调用：


```java
Runnable runabbleA=new ThreadA();
Thread a=new Thread(runabbleA,"A");                
a.start();
Runnable runabbleB=new ThreadB();
Thread b=new Thread(runabbleB,"B");                
b.start();
```