سؤال

Is this good OO Design assuming you want every inheriting class to be a infinite Thread ? Any better/more elegant way of doing similar thing?

public abstract class Base implements Runnable {

protected abstract void doSomething();

public void run() {

    while ( true ) {
        Thread.sleep(1000);
        doSomething();
    }
}
}
هل كانت مفيدة؟

المحلول

If you only want doSomething to execute every second, you could move the task to its own Runnable and schedule it with a ScheduledExecutorService. This way you can reduce the number of threads in your program and save resources.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top