请问如何判断一个线程是否处于暂停?

dash_running 2007-09-17 12:06:49
问题是这样的,线程A对一个数做加法,超过5时暂停,线程B对同一个数做减法,等于0时暂停,线程C对这个数定期检查,如果该数小于3,并且A是暂停状态,那么就唤醒A继续加,如果该数大于2,并且B处于暂停状态,就让B做减法.

如何判断某一时刻线程A或者B是不是用wait() 让自己处于等待状态?
...全文
524 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
dash_running 2007-09-21
  • 打赏
  • 举报
回复
多谢各位,觉得java的多线程设计有点别扭,写同步的代码不是在线程类里来写,而是在竞争资源类里来写同步的代码里。不管怎么样,知道怎么写了就好。
冰思雨 2007-09-19
  • 打赏
  • 举报
回复
要是用wait/notify就是挺麻烦的。我编了一个小程序,四个类。楼主看一下吧。测了一下,还算成功。我把初始数值设置成1了,因为,如果设置成0,B线程一跑,有可能减成负数,这样,要是加不到整数,就没有什么意思了。这也许是个小bug吧。
代码入下:(我用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毫秒。
}

}

}
sunboylyg 2007-09-19
  • 打赏
  • 举报
回复
在线程A、B的类里面增加一个boolean标志flag,wait()前flag=true,wait()后flag=false,然后再设一个getFlag()的公共方法给线程C调用
dash_running 2007-09-18
  • 打赏
  • 举报
回复
自己顶,没有人会吗????
chenxw_mail 2007-09-18
  • 打赏
  • 举报
回复
getState()返回该线程的状态
isAlive()测试线程是否处于活动状态
activeCount()返回当前线程的线程组中活动线程的数目

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧