Welcome

首页 / 软件开发 / JAVA / java中的锁池及等待池

java中的锁池及等待池2016-08-26
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;}@Overridepublic 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;}@Overridepublic 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();}}