---
title: "静态锁和实例锁"
author: "benx"
date: "2011-07-28T18:21:13Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2011-07-28T18:21:13Z"
id: 1135085
url: "https://benx.iteye.com/blog/1135085"
---

Java中可以对静态方法和实例方法使用synchronized

 

当在静态方法前面加synchronized 表示锁定class , 当多个线程同时调用静态方法时会阻塞

 

当在实例方法前面加synchronized 表示锁定class的单个实例 , 当多个线程同时调用class的实例的实例方法时会阻塞

 

注意：静态方法synchronized 和实例方法synchronized 互不干扰，也就是说当静态方法锁后，不影响实例方法调用，反过来一样

 

 

```
package com.lottery;

public class Test {

	public static void main(String[] args) {
		final Lock lock = new Lock();

		new Thread() {
			public void run() {
				Lock.method2();
			}
		}.start();

		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		new Thread() {
			public void run() {
				lock.method1();
				//Lock.method2();
			}
		}.start();
	}
}

class Lock {

	public synchronized void method1() {
		System.out.println("method1 start");
		try {
			Thread.sleep(1000 * 10);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("method1 end");
	}

	public static synchronized void method2() {
		System.out.println("method2 start");
		try {
			Thread.sleep(1000 * 10);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("method2 end");
	}
}
```