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();
}
}
java中的锁池及期待池
最后更新 2017-11-02 08:00 星期四 所属:
JAVA 教程 浏览:936
