java 執行緒淺解03[執行緒同步以及經典死鎖]

我就是曹總發表於2019-05-11

執行緒中通過新增synchronized關鍵字來新增鎖,可以鎖物件,鎖方法,如下所示

package com.thread;

//執行緒同步 synchronized
public class Thread06_synchronized  implements Runnable {

	Timeer t1=new Timeer();
	public static void main(String[] args) {
		Thread06_synchronized ts=new Thread06_synchronized();
		Thread t2=new Thread(ts);
		Thread t3=new Thread(ts);
		t2.setName("t1");
		t3.setName("t2");
		t2.start();
		t3.start();
		
	}
	public void run() {
		t1.add(Thread.currentThread().getName());
	}
	 
} 

class Timeer{
	private static int num=0;
	public  void add(String name){
		synchronized(this){
		num++;
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(name+",你是第"+num+"使用這個物件滴");
		}
	}
}



執行結果:
t1,你是第1使用這個物件滴
t2,你是第2使用這個物件滴

ps:可將鎖關鍵字去掉,檢視結果



死鎖有可能涉及到,先給出例子,

案例場景:有兩個物件,兩把鎖,每一把鎖都需要操作兩個物件才能正常,如程式碼

package com.thread;

//執行緒同步 synchronized
public class Thread06_deadLock implements Runnable {
	private int flag = 1;
	static Object o1 = new Object(), o2 = new Object();

	public void run() {
		System.out.println("flag=" + flag);
		if (flag == 1) {
			synchronized (o1) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				synchronized (o2) {
					System.out.println( flag);
				}
			}
			
		}
	
	
	if (flag == 0) {
		synchronized (o2) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			synchronized (o1) {
				System.out.println(flag);
			}
		}
	}
}

	
	public static void main(String[] args) {
		Thread06_deadLock td1=new Thread06_deadLock();
		Thread06_deadLock td2=new Thread06_deadLock();
		td1.flag=1;
		td2.flag=0;
		Thread t1=new Thread(td1);
		Thread t2=new Thread(td2);
		t1.start();
		t2.start();
		
	}
	
}



執行結果:
flag=1
flag=0
就卡住了,形成死鎖,如感興趣滴筒靴可以百度下哲學家吃飯滴問題,更容易理解





內容均為作者獨立觀點,不代表八零IT人立場,如涉及侵權,請及時告知。

相關文章