java多執行緒之(synchronized)

為不為發表於2018-12-21
public class MyThread {
	private static int i=5;
	public static synchronized void print(String a) {
		if(a.equals("a")) {
			i--;
			System.out.println("a "+i);
		}else {
			i=i-2;
			System.out.println("b "+i);
		}
		System.out.println("last "+i);
	}
	
	public static void main(String[] args) {
		final MyThread thread=new MyThread();
		final MyThread thread1=new MyThread();
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				thread.print("a");
			}
		}).start();
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				thread1.print("b");
			}
		}).start();


	}


}
a 4
last 4
b 2
last 2

在變數和方法上加static ,在該類的所有物件是具有相同的引用的

public class MyThread {
	private  int i=5;
	public  synchronized void print(String a) {
		if(a.equals("a")) {
			i--;
			System.out.println("a "+i);
		}else {
			i=i-2;
			System.out.println("b "+i);
		}
		System.out.println("last "+i);
	}
	
	public static void main(String[] args) {
		final MyThread thread=new MyThread();
		final MyThread thread1=new MyThread();
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				thread.print("a");
			}
		}).start();
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				thread1.print("b");
			}
		}).start();


	}


}
a 4
last 4
b 3
last 3

由此可見,synchronized 一個物件一把鎖,多個執行緒多個鎖
Synchronized 其他特點
1.Synchronized 鎖重入:作用避免死鎖
2.出現異常時,鎖自動釋放

相關文章