java 例子1
(2012-01-08 10:52:56)
标签:
杂谈 |
分类: 计算机相关 |
要求写两个线程,一个线程将某个对象的某个成员变量的值加1,而另外一个线程将这个成员变量的值减1.使得该变量的值始终处于[0,2].初始值为0.
- package
com.tju; - class
Target -
{
-
int count; -
-
synchronized void increase() -
{ -
== 2) -
{ -
-
{ -
wait(); -
} -
(InterruptedException e) -
{ -
e.printStackTrace(); -
} -
} -
count++; -
System.out.println(Thread.currentThread().getName() + + count); -
notify(); -
} -
-
synchronized void decrease() -
{ -
== 0) -
{ -
-
{ -
-
-
wait(); -
} -
(InterruptedException e) -
{ -
e.printStackTrace(); -
} -
} -
count--; -
System.out.println(Thread.currentThread().getName() + + count); -
-
-
notify(); -
} -
}
- class
Increase extendsThread -
{
-
Target t; -
-
Increase(Target t) -
{ -
= t; -
} -
-
void run() -
{ -
i 0= ;i 30;< i++) -
{ -
-
{ -
Thread.sleep(( -
} -
(InterruptedException e) -
{ -
e.printStackTrace(); -
} -
-
t.increase(); -
} -
-
} -
-
}
- class
Decrease extendsThread -
{
-
-
Target t; -
Decrease(Target t) -
{ -
= t; -
} -
-
-
void run() -
{ -
i 0= ; 30i < ; i++) -
{ -
-
{ -
-
-
Thread.sleep(( -
} -
(InterruptedException e) -
{ -
e.printStackTrace(); -
} -
-
t.decrease(); -
-
} -
-
} -
-
}
-
- public
class Test -
{
-
static void main(String[] args) -
{ -
Target t = Target(); -
-
Thread t1 = Increase(t); -
t1.setName( -
Thread t2 = Decrease(t); -
t2.setName( -
-
t1.start(); -
t2.start(); -
} -
}
前一篇:a good father
后一篇:romantic or not