问题是这样的,线程A对一个数做加法,超过5时暂停,线程B对同一个数做减法,等于0时暂停,线程C对这个数定期检查,如果该数小于3,并且A是暂停状态,那么就唤醒A继续加,如果该数大于2,并且B处于暂停状态,就让B做减法.如何判断某一时刻线程A或者B是不是用wait() 让自己处于等待状态?

解决方案 »

  1.   

    getState()返回该线程的状态
    isAlive()测试线程是否处于活动状态
    activeCount()返回当前线程的线程组中活动线程的数目
      

  2.   

    在线程A、B的类里面增加一个boolean标志flag,wait()前flag=true,wait()后flag=false,然后再设一个getFlag()的公共方法给线程C调用
      

  3.   

    要是用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毫秒。
    } }}
      

  4.   

    多谢各位,觉得java的多线程设计有点别扭,写同步的代码不是在线程类里来写,而是在竞争资源类里来写同步的代码里。不管怎么样,知道怎么写了就好。