在 java 中延迟 class 的方法

delay a method of a class in java

我想在调用 buzzStart() 时延迟,然后在调用 buzzStop 时延迟 延迟完成。

我该怎么做?

public class BuzzerSignaler{

     private long timeout;
     public void buzzStart() throws Exception {
        this.timeout = 0;
        action('1');
     }

     public void buzzStart(long timeout) throws Exception {
         this.timeout = timeout;
        //some code for delay
     }

     public void buzzStop() throws Exception {
        //stop delay
        action('0');
     }

     private void action(char offOn) throws Exception {

     }
    }

是这样的吗?

public class BuzzerSignaler {
    private long timeout;
    private volatile boolean shouldStop = false;

    public static void main(String... args) {
        BuzzerSignaler signaler = new BuzzerSignaler();
        try {
            signaler.buzzStart(100);
            Thread.sleep(1000);
            signaler.buzzStop();
        } catch (Exception ignored) {
            ignored.printStackTrace();
        }
    }

    public void buzzStart() throws Exception {
        this.timeout = 0;
        action('1');
    }

    public void buzzStart(long timeout) throws Exception {
        this.timeout = timeout;
        new Thread(() -> {
            while (shouldStop == false) {
                try {
                    Thread.currentThread().sleep(this.timeout);
                    action('1');
                } catch (Exception ignored) {
                    ignored.printStackTrace();
                }
            }
        }).start();
    }

    public void buzzStop() throws Exception {
        //stop delay
        shouldStop = true;
        action('0');
    }

    private void action(char offOn) throws Exception {
        System.out.println("I'm working..." + offOn);
    }
}

输出将是:

I'm working...1
I'm working...1
I'm working...1
I'm working...1
I'm working...1
I'm working...1
I'm working...1
I'm working...1
I'm working...1
I'm working...0
I'm working...1
  public void buzzStart(long delayMillis) throws Exception {

    buzzStart();

    long timeout = System.currentTimeMillis() + (10 * delayMillis);
    shouldStop = false;

    new Thread(() -> {
        while (shouldStop == false && System.currentTimeMillis() < timeout) {
            try {
                Thread.currentThread().sleep(delayMillis);
            } catch (Exception ignored) {
                ignored.printStackTrace();
            }
        }
        try {
            buzzStop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }).start();
}