程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> java中的鎖池及等待池

java中的鎖池及等待池

編輯:關於JAVA
package com.tju;
class Target
{
	private int count;
	
	public synchronized void increase()
	{
		if(count == 2)
		{
			try
			{
				wait();
			} 
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
		count++;
		System.out.println(Thread.currentThread().getName() + ":" + count);
		notify();
	}
	
	public synchronized void decrease()
	{
		if(count == 0)
		{
			try
			{
				//等待,由於Decrease線程調用的該方法,
				//URL:http://www.bianceng.cn/Programming/Java/201608/50397.htm
				//所以Decrease線程進入對象t(main函數中實例化的)的等待池,並且釋放對象t的鎖
				wait();//Object類的方法
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
		count--;
		System.out.println(Thread.currentThread().getName() + ":" + count);
		
		//喚醒線程Increase,Increase線程從等待池到鎖池
		notify();
	}
}
class Increase extends Thread
{
	private Target t;
	
	public Increase(Target t)
	{
		this.t = t;
	}
	@Override
	public void run()
	{	
		for(int i = 0 ;i < 30; i++)
		{
			try
			{
				Thread.sleep((long)(Math.random()*500));
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			
			t.increase();
		}
		
	}
	
}
class Decrease extends Thread
{
	
	private Target t;
	public Decrease(Target t)
	{
		this.t = t;
	}
	
	@Override
	public void run()
	{
		for(int i = 0 ; i < 30 ; i++)
		{
			try
			{
				//隨機睡眠0~500毫秒
				//sleep方法的調用,不會釋放對象t的鎖
				Thread.sleep((long)(Math.random()*500));
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			
			t.decrease();
			
		}
		
	}
	
}

public class Test
{
	public static void main(String[] args)
	{
		Target t = new Target();
		
		Thread t1 = new Increase(t);
		t1.setName("Increase");
		Thread t2 = new Decrease(t);
		t2.setName("Decrease");
		
		t1.start();
		t2.start();
	}
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved