1. 程式人生 > >java併發程式設計一一多執行緒之間通訊(一)

java併發程式設計一一多執行緒之間通訊(一)

1.多執行緒之間如何實現通訊

多執行緒之間通訊,其實就是多個執行緒在操作同一個資源,但是操作的動作不同。

1.1什麼是多執行緒之間通訊?

需求:第一個執行緒寫入(input)使用者,另一個執行緒讀取(out)使用者。實現讀一個,寫一個操作。

1.2多執行緒之間通訊需求?

這裡寫圖片描述

2.程式碼實現基本實現

2.1共享資源源實體類

程式碼示例:

class Res {
	public String userSex;
	public String userName;
}

2.2輸入執行緒資源

class IntThrad extends Thread {
	private Res res;

	public IntThrad(Res res) {
		this.res = res;
	}

	@Override
	public void run() {
		int count = 0;
		while (true) {
				if (count == 0) {
					res.userName = "小明";
					res.userSex = "男";
				} else {
					res.userName = "小紅";
					res.userSex = "女";
				}
				count = (count + 1) % 2;
			}
	}
}

2.3輸出執行緒

class OutThread extends Thread {
	private Res res;

	public OutThread(Res res) {
		this.res = res;
	}

	@Override
	public void run() {
		while (true) {
				System.out.println(res.userName + "--" + res.userSex);
		}
	}
}

2.4執行程式碼

Res res = new Res();
IntThrad intThrad = new IntThrad(res);
OutThread outThread = new OutThread(res);
intThrad.start();
outThread.start();

2.5執行程式碼結果

結果:資料會發生錯亂,造成執行緒安全問題。

2.6解決執行緒安全問題

在IntThrad 加上synchronized

class IntThrad extends Thread {
	private Res res;

	public IntThrad(Res res) {
		this.res = res;
	}

	@Override
	public void run() {
		int count = 0;
		while (true) {
			synchronized (res) {
				if (count == 0) {
					res.userName = "小明";
					res.userSex = "男";
				} else {
					res.userName = "小紅";
					res.userSex = "女";
				}
				count = (count + 1) % 2;
			}

		}
	}
}

輸出執行緒加上synchronized

class Res {
	public String userName;
	public String sex;
}

class InputThread extends Thread {
	private Res res;

	public InputThread(Res res) {
		this.res = res;
	}

	@Override
	public void run() {
		int count = 0;
		while (true) {
			 synchronized (res) {
			if (count == 0) {
				res.userName = "小明";
				res.sex = "男";
			} else {
				res.userName = "小紅";
				res.sex = "女";
			}
			count = (count + 1) % 2;
		}

		}
	}
}

class OutThrad extends Thread {
	private Res res;

	public OutThrad(Res res) {
		this.res = res;
	}

	@Override
	public void run() {
		while (true) {
			synchronized (res) {
				System.out.println(res.userName + "," + res.sex);
			}
		}

	}
}

public class ThreadDemo01 {

	public static void main(String[] args) {
		Res res = new Res();
		InputThread inputThread = new InputThread(res);
		OutThrad outThrad = new OutThrad(res);
		inputThread.start();
		outThrad.start();
	}

}

2.7wait、notify方法

  1. 因為涉及到物件鎖,他們必須都放在synchronized中來使用。wait、notify一定要在synchronized
    裡面進行使用。
  2. wait必須暫定當前正在執行的執行緒,並釋放資源鎖,讓其他執行緒可以有機會執行。
  3. notify和notifall:喚醒因鎖池中的執行緒使之執行。
    注意:一定要線上程同步中使用
class Res {
	public String userSex;
	public String userName;
	//執行緒通訊標識
	public boolean flag = false;
}

 
class IntThrad extends Thread {
	private Res res;

	public IntThrad(Res res) {
		this.res = res;		
	}

	@Override
	public void run() {
		int count = 0;
		while (true) {
			synchronized (res) {
				if (res.flag) {
					try {
					   // 當前執行緒變為等待,但是可以釋放鎖
						res.wait();
					} catch (Exception e) {

					}
				}
				if (count == 0) {
					res.userName = "小明";
					res.userSex = "男";
				} else {
					res.userName = "小紅";
					res.userSex = "女";
				}
				count = (count + 1) % 2;
				res.flag = true;
				// 喚醒當前執行緒
				res.notify();
			}

		}
	}
}
 
class OutThread extends Thread {
	private Res res;

	public OutThread(Res res) {
		this.res = res;
	}

	@Override
	public void run() {
		while (true) {
			synchronized (res) {
				if (!res.flag) {
					try {
						res.wait();
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
				System.out.println(res.userName + "--" + res.userSex);
				res.flag = false;
				res.notify();
			}
		}
	}
}
 
public class ThreaCommun {
	public static void main(String[] args) {
		Res res = new Res();
		IntThrad intThrad = new IntThrad(res);
		OutThread outThread = new OutThread(res);
		intThrad.start();
		outThread.start();
	}
}

2.8wait與sleep區別

對於sleep()方法,我們首先要知道該方法書屬於Thread類中的,而wait() 方法,則是屬於Object類中的。
sleep()方法導致了程式暫停執行指定的時間,讓出cpu該其它執行緒,但是他的監控狀態依然保持者,
當指定的時間到了又會自動恢復執行狀態。
在呼叫sleep()方法的時候,執行緒不會釋放物件鎖。
而當呼叫wait() 方法的時候,執行緒會放棄物件鎖,進而等待此物件的等待鎖定池,只有針對此物件
呼叫notify()方法後本執行緒才進入物件索定池準備
獲取物件鎖進入執行狀態。

3.Lock鎖

在jdk1.5 之後,併發包中新增了Lock介面(以及相關實現類)用來實現鎖功能,Lock介面提供了與
synchronized關鍵字類似的同步功能,但需要在使用時手動獲取鎖和釋放鎖。

3.1Lock寫法

Lock lock  = new ReentrantLock();
lock.lock();
try{
//可能會出現執行緒安全的操作
}finally{
//一定在finally中釋放鎖
//也不能把獲取鎖在try中進行,因為有可能在獲取鎖的時候丟擲異常
  lock.ublock();
}

3.2.Lock與synchronized關鍵字的區別

  1. Lock介面可以嘗試非阻塞地獲取鎖,當前執行緒嘗試獲取鎖。如果這一時刻沒有被其他執行緒獲取到,
    則成功獲取並持有鎖。
  2. Lock介面能被中斷的獲取鎖與synchronized不同,獲取到鎖的執行緒能夠相應中斷,當獲取到鎖的
    執行緒被中斷時,中斷異常將會被丟擲,同時鎖會被釋放。
  3. Lock介面在指定的截止時間之前獲取鎖,如果截止時間到了依舊無法獲取鎖,則返回。

3.3Condition用法

Condition的功能類似於在傳統的執行緒技術中的,Object.wait() 和 Obect.notify() 的功能。
程式碼示例:

Condition condition = lock.newCondition();
res. condition.await();  類似wait
res. Condition. Signal() 類似notify
 
class Res {
	public String userName;
	public String sex;
	public boolean flag = false;
	Lock lock = new ReentrantLock();
}

class InputThread extends Thread {
	private Res res;
	Condition newCondition;
	public InputThread(Res res,	Condition newCondition) {
		this.res = res;
		this.newCondition=newCondition;
	}

	@Override
	public void run() {
		int count = 0;
		while (true) {
			// synchronized (res) {

			try {
				res.lock.lock();
				if (res.flag) {
					try {
//						res.wait();
						newCondition.await();
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
				if (count == 0) {
					res.userName = "小明";
					res.sex = "男";
				} else {
					res.userName = "小紅";
					res.sex = "女";
				}
				count = (count + 1) % 2;
				res.flag = true;
//				res.notify();
				newCondition.signal();
			} catch (Exception e) {
				// TODO: handle exception
			}finally {
				res.lock.unlock();
			}
		}

		// }
	}
}

class OutThrad extends Thread {
	private Res res;
	private Condition newCondition;
	public OutThrad(Res res,Condition newCondition) {
		this.res = res;
		this.newCondition=newCondition;
	}

	@Override
	public void run() {
		while (true) {
//			synchronized (res) {
			try {
				res.lock.lock();
				if (!res.flag) {
					try {
//						res.wait();
						newCondition.await();
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
				System.out.println(res.userName + "," + res.sex);
				res.flag = false;
//				res.notify();
				newCondition.signal();
			} catch (Exception e) {
				// TODO: handle exception
			}finally {
				res.lock.unlock();
			}
//			}
		}

	}
}

public class ThreadDemo01 {

	public static void main(String[] args) {
		Res res = new Res();
		Condition newCondition = res.lock.newCondition();
		InputThread inputThread = new InputThread(res,newCondition);
		OutThrad outThrad = new OutThrad(res,newCondition);
		inputThread.start();
		outThrad.start();
	}

}