java 例子1
(2012-01-08 10:52:56)
标签:
杂谈 |
分类: 计算机相关 |
要求写两个线程,一个线程将某个对象的某个成员变量的值加1,而另外一个线程将这个成员变量的值减1.使得该变量的值始终处于[0,2].初始值为0.
- package
com.tju; - class
Target -
{
-
privateint count; -
-
publicsynchronized void increase() -
{ -
if(count== 2) -
{ -
try -
{ -
wait(); -
} -
catch(InterruptedException e) -
{ -
e.printStackTrace(); -
} -
} -
count++; -
":"System.out.println(Thread.currentThread().getName() + + count); -
notify(); -
} -
-
publicsynchronized void decrease() -
{ -
if(count== 0) -
{ -
try -
{ -
//等待,由于Decrease线程调用的该方法, -
//所以Decrease线程进入对象t(main函数中实例化的)的等待池,并且释放对象t的锁 -
//Object类的方法wait(); -
} -
catch(InterruptedException e) -
{ -
e.printStackTrace(); -
} -
} -
count--; -
":"System.out.println(Thread.currentThread().getName() + + count); -
-
//唤醒线程Increase,Increase线程从等待池到锁池 -
notify(); -
} -
}
- class
Increase extendsThread -
{
-
privateTarget t; -
-
publicIncrease(Target t) -
{ -
this.t= t; -
} -
@Override -
publicvoid run() -
{ -
for(inti 0= ;i 30;< i++) -
{ -
try -
{ -
long)(Math.random()*500));Thread.sleep(( -
} -
catch(InterruptedException e) -
{ -
e.printStackTrace(); -
} -
-
t.increase(); -
} -
-
} -
-
}
- class
Decrease extendsThread -
{
-
-
privateTarget t; -
publicDecrease(Target t) -
{ -
this.t= t; -
} -
-
@Override -
publicvoid run() -
{ -
for(inti 0= ; 30i < ; i++) -
{ -
try -
{ -
//随机睡眠0~500毫秒 -
//sleep方法的调用,不会释放对象t的锁 -
long)(Math.random()*500));Thread.sleep(( -
} -
catch(InterruptedException e) -
{ -
e.printStackTrace(); -
} -
-
t.decrease(); -
-
} -
-
} -
-
}
-
- public
class Test -
{
-
publicstatic void main(String[] args) -
{ -
newTarget t = Target(); -
-
newThread t1 = Increase(t); -
"Increase");t1.setName( -
newThread t2 = Decrease(t); -
"Decrease");t2.setName( -
-
t1.start(); -
t2.start(); -
} -
}
前一篇:a good father
后一篇:romantic or not

加载中…