簡體   English   中英

多線程中的Java調用子類方法

[英]Java call child class method in multithreading

public abstract class Event implements Runnable {

  public void run() {
    try {
        Thread.sleep(delayTime);
        action();
    } catch(Exception e) {e.printStackTrace();}
  } 

}

我上面有這個事件類,當我嘗試啟動線程時,它運行線程的第一個命令-Thread.sleep(delayTime); 由於Event類是抽象類,因此我想運行其某些子類方法。 例如,當我調用action()時; 它應該從下面的子類中運行action方法

public class ThermostatNight extends Event {
  public ThermostatNight(long delayTime) {
    super(delayTime);
  }
  public void action() {
    System.out.println(this);
    thermostat = "Night";
  }
  public String toString() {return "Thermostat on night setting";}
}

此類子類很多,如ThermostatDay,FanOn,FanOff,它們與上述非常相似。 我該怎么辦call action(); 從Event類的run()命令調用睡眠之后?

有任何想法嗎?

感謝您的幫助!

創建和創建事件類型的實例變量,以及將事件作為參數的構造函數

    public class Event implements Serializable, Runnable {
       private Event childClass;

       public Event(long delayTime, Event childClass) {
         this.delayTime = delayTime;
         this.childClass = childClass;

       }

       public void run() {
          try {
            Thread.sleep(delayTime);
            childClass.action();
          } catch(Exception e) {e.printStackTrace();} 
       }
    } 

我在這里意識到了問題。

您可以看到在下面的try {}中調用了action():

  public void run() {
    try {
        Thread.sleep(delayTime);
        action();
    } catch(Exception e) {e.printStackTrace();}
  } 

如果按如下所示將其推出,則代碼應該可以正常工作。

public void run() {
    try {
        Thread.sleep(delayTime);
    } catch(Exception e) {e.printStackTrace();}
      action();
  } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM