在java中通知线程

时间:2014-06-09 10:56:58

标签: java

我有一个问题,我在文件ThreadRunner.java中创建了一个类ThreadRunner。类有1个属性,RunnersName是一个对象。

class ThreadRunner implements Runnable {

    String RunnersName = "";
    boolean isRun = false;
    int countTime;

public String getRunnersName() {
    return RunnersName;
}

public void setRunnersName(String RunnersName) {
    this.RunnersName = RunnersName;
}

public boolean isIsRun() {
    return isRun;
}

public void setIsRun(boolean isRun) {
    this.isRun = isRun;
}

public ThreadRunner(String RunnersName,
        int RunnersSpeed,
        int RestPercentage) {
    this.RunnersName = RunnersName;
}

@Override
public void run() {
    while (true) {
        if (isRun) {
            count++;
            System.out.println(RunnersName + " is running with " + countTime +"times");
            isRun = false;
        } 
    }
}

}

主类(RunChampion.java)中的

    ThreadRunner dog = new ThreadRunner("Dog");
    ThreadRunner cat= new ThreadRunner("Duck");
    Thread a = new Thread(dog);
    Thread b = new Thread(cat);
    a.start();
    b.start();
    while (true) {
        try {
            Thread.sleep(100);

            int value = (int) (Math.random() * 100);
            System.out.println("Value is " + value);

            if (value >= 50 && value < 70) {
                dog.setIsRun(true);
            } else {
                dog.setIsRun(false);
            }

            if (value >= 60 && value < 90) {
                cat.setIsRun(true);
            } else {
                cat.setIsRun(false);
            }

        } catch (InterruptedException ex) {
            Logger.getLogger(RunChampion.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println(ex);
        }
   }

我想当cat或dog的countTime值= 10时,两个线程(a,b)会破坏。 我该怎么办?

全部谢谢

0 个答案:

没有答案