ITeye博客

静态锁和实例锁

benx · 2011-07-28 18:21 · java · 编程语言 · Markdown

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");
	}
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。