问题是这样的,线程A对一个数做加法,超过5时暂停,线程B对同一个数做减法,等于0时暂停,线程C对这个数定期检查,如果该数小于3,并且A是暂停状态,那么就唤醒A继续加,如果该数大于2,并且B处于暂停状态,就让B做减法.如何判断某一时刻线程A或者B是不是用wait() 让自己处于等待状态?
解决方案 »
- Swing GUI重用问题
- MM7 报出的 java.lang.IndexOutOfBoundsException: Index: 1, Size: 1 错误怎么解决?
- 看哪位大侠能把java中的所有包及其应用列举出来……
- 纯数据byte data[x*y]怎么生成JPEG or gif等图片?
- SQL Server中支持image到Blob的装还吗?
- 一个关于接口实现多重继承的问题,???
- 关于Method的问题。
- 奇怪的问题!!!个位大虾帮忙!!!!
- 那位大虾知道怎样得到本机的IP地址或计算机名?
- 我实在无能为力了,大侠们,救命!!!!!!
- button acction 读取 txt文件
- 请教一个字符编码的问题(unicode)
isAlive()测试线程是否处于活动状态
activeCount()返回当前线程的线程组中活动线程的数目
代码入下:(我用sleep方法主要目地是为了测试的时候好看出结果。)
public class A extends Thread { private Num number;
public A(Num number) {
super();
this.number = number;
} public void run() {
while(true){
try {
number.aOperate(this);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}}
public class B extends Thread { private Num number;
public B(Num number) {
super();
this.number = number;
} public void run() {
while(true){
try {
number.bOperate(this);
} catch (InterruptedException e) {
e.printStackTrace();
} }
}}
public class Num { private int number =1 ;
private boolean aWait=false;
private boolean bWait=false;
public synchronized boolean aOperate(Thread thread) throws InterruptedException{
number++;
System.out.println(thread.getName()+"\t"+number);
Thread.sleep(3);
if(number>5){
aWait = true;
while(aWait){
wait();
}
}
return false;
}
public synchronized boolean bOperate(Thread thread) throws InterruptedException{
number--;
System.out.println(thread.getName()+"\t"+number);
Thread.sleep(3);
if(number == 0){
bWait = true;
while(bWait){
wait();
}
}
return false;
}
public synchronized boolean cOperator(Thread thread){
System.out.println(thread.getName()+"\t"+number);
if((number<3&&aWait)){
aWait = false;
}
if((number>2)&&bWait){
bWait = false;
}
notifyAll();
return false;
}
}public class C { public static void main(String[] args) throws InterruptedException {
Num number = new Num();
A a = new A(number);
B b = new B(number);
a.start();
b.start();
while(true){
number.cOperator(Thread.currentThread());
Thread.sleep(1);//定时检查,我设置成了1毫秒。
} }}