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

java多執行緒之間通訊

1 實現一個執行緒+1 一個執行緒 -1

class Share511 {
	public int a = 0;
}
class Thread552 implements Runnable{
	Share511 share;
	@Override
	public void run() {
		while(true){
			synchronized (share) {
				int a = share.a;
				if(a == 0){
					share.a =a+1;
					System.out.println("a+1 " + share.a);
					share.notify();
				}else{
					try {
						share.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}	
		}
	}
	public Thread552(Share511 share) {
		this.share = share;
	}
}
class Thread553 implements Runnable{
	Share511 share;
	@Override
	public void run() {
		while(true){
			synchronized (share) {
				int a = share.a;
				if(a == 1){
					share.a = a - 1;
					System.out.println("a-1 " + share.a);
					share.notify();
				}else{
					try {
						share.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	public Thread553(Share511 share) {
		this.share = share;
	} 	
}
public class Thread5 {
	public static void main(String[] args) {
		Share511 share511 = new Share511();
		Thread thread552 = new Thread(new Thread552(share511));
		thread552.start();
		Thread thread553 = new Thread(new Thread553(share511));
		thread553.start();
	}
}

2 sleep()與wait()區別

  1. sleep()屬於方法是屬於Thread類中的方法
  2. sleep()不會釋放物件鎖wait()物件鎖

3 Lock寫法:

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

4 Condition用法

Condition condition = lock.newCondition();
condition.await();  類似wait
Condition.signal() 類似notify

5 守護執行緒
Java中有兩種執行緒一種是使用者執行緒,另一種是守護執行緒
當程序不存在或主執行緒停止守護執行緒也會被停止
使用setDaemon(true)方法設定為守護執行緒