1. 程式人生 > >多執行緒之間實現通訊

多執行緒之間實現通訊

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

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

多執行緒之間通訊需求

需求:第一個執行緒寫入(input)使用者,另一個執行緒取讀取(out)使用者.實現讀一個,寫一個操作。 在這裡插入圖片描述 共享資源源實體類

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

輸入執行緒資源

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

輸出執行緒

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

執行程式碼

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

執行結果: 在這裡插入圖片描述 資料發生錯亂,造成執行緒安全問題

解決執行緒安全問題

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

}

wait()、notify、notifyAll()方法

wait()、notify()、notifyAll()是三個定義在Object類裡的方法,可以用來控制執行緒的狀態。
這三個方法最終呼叫的都是jvm級的native方法。隨著jvm執行平臺的不同可能有些許差異。
 如果物件呼叫了wait方法就會使持有該物件的執行緒把該物件的控制權交出去,然後處於等待狀態。
如果物件呼叫了notify方法就會通知某個正在等待這個物件的控制權的執行緒可以繼續執行。
如果物件呼叫了notifyAll方法就會通知所有等待這個物件控制權的執行緒繼續執行。

注意:一定要線上程同步中使用,並且是同一個鎖的資源

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

執行結果:

在這裡插入圖片描述

wait與sleep區別?

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

JDK1.5-Lock

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

Lock寫法

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

Lock 介面與 synchronized 關鍵字的區別

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

Condition用法

Condition的功能類似於在傳統的執行緒技術中的,Object.wait()和Object.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();
	}

}

在這裡插入圖片描述