天天看點

對于靜态方法與非靜态方法使用關鍵字synchronized

對于非靜态同步方法:如果使用synchronized關鍵字的話,鎖對象是this

public class Test1 {
	public static void main(String[] args) {
		final Printer p = new Printer();
		new Thread() {
			public void run() {
				while(true) {
					p.print1();
					}
			}
		}.start();
		new Thread() {
			public void run() {
				while(true) {
				p.print2();
				}
			}
		}.start();
	}
}
class Printer{
	public synchronized void print1() {//非靜态同步方法
		System.out.print("我");
		System.out.print("是");
		System.out.print("小");
		System.out.print("仙");
		System.out.print("女");
		System.out.print("\r\n");
	}
	public void print2() {
		synchronized(this) {//同步代碼塊,使用this鎖對象
			System.out.print("我");
			System.out.print("愛");
			System.out.print("學");
			System.out.print("習");
			System.out.print("\r\n");
		}
	}
           

而對于靜态同步方法,由于靜态方法優先于對象存在,是以鎖對象不是this,而是該類的位元組碼對象(.class檔案)

class Printer{
public static void print1() {
		synchronized(Test1.class) {
			System.out.println("同步代碼塊1");
		}
	}
	public static void print2() {
		synchronized(Test1.class) {
			System.out.println("同步代碼塊2");
		}
	}
}