1. 程式人生 > >JUC學習筆記(2)—執行緒間通訊

JUC學習筆記(2)—執行緒間通訊

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class ShareData
{
	private int number = 0;
	private Lock lock = new ReentrantLock();
	private Condition condition = lock.newCondition();
	
	public void increment() throws InterruptedException
	{
		lock.lock();
		try 
		{
			while(number != 0)
			{
				condition.await();//this.wait();
			}
			//2 幹活
			++number;
			System.out.println(Thread.currentThread().getName()+"\t"+number);
			//3 通知
			condition.signalAll();//this.notifyAll();			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}
	
	public void decrement() throws InterruptedException
	{
		lock.lock();
		try 
		{
			while(number == 0)
			{
				condition.await();//this.wait();
			}
			//2 幹活
			--number;
			System.out.println(Thread.currentThread().getName()+"\t"+number);
			//3 通知
			condition.signalAll();//this.notifyAll();			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}
		
	
	
	/*public synchronized void increment() throws InterruptedException
	{
		//1 判斷
		//if(number != 0)
		while(number != 0)
		{
			this.wait();// A......C......
		}
		//2 幹活
		++number;
		System.out.println(Thread.currentThread().getName()+"\t"+number);
		//3 通知
		this.notifyAll();
	}
	
	public synchronized void decrement() throws InterruptedException
	{
		//1 判斷
		//if(number == 0)
		while(number == 0)
		{
			this.wait();
		}
		//2 幹活
		--number;
		System.out.println(Thread.currentThread().getName()+"\t"+number);
		//3 通知
		this.notifyAll();
	}	*/
	
}


/**
 * 
 * @Description: 
 * 現在兩個執行緒,
 * 可以操作初始值為零的一個變數,
 * 實現一個執行緒對該變數加1,一個執行緒對該變數減1,
 * 交替,來10輪,變數初始值為零。
 * @author zzyy
 * @date 2018年3月15日
 * 1 多執行緒編寫套路------上
 * 		1.1	執行緒		操作(例項方法)		資源類
 * 		1.2  高內聚  低耦合
 * 
 * 2 多執行緒編寫套路------下
 * 		2.1 判斷
 * 		2.2 幹活
 * 		2.3 通知
 */
public class NotifyWaitDemo
{
	public static void main(String[] args)
	{
		ShareData sd = new ShareData();
		
		new Thread(() -> {
			for (int i = 1; i <=10; i++) 
			{
				try 
				{
					Thread.sleep(200);
					sd.increment();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}, "AA").start();
		
		new Thread(() -> {
			for (int i = 1; i <=10; i++) 
			{
				try 
				{
					Thread.sleep(300);
					sd.decrement();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}, "BB").start();		
		
		new Thread(() -> {
			for (int i = 1; i <=10; i++) 
			{
				try 
				{
					Thread.sleep(400);
					sd.increment();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}, "CC").start();
		
		new Thread(() -> {
			for (int i = 1; i <=10; i++) 
			{
				try 
				{
					Thread.sleep(500);
					sd.decrement();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}, "DD").start();			
		
		
	}
}