Thread which executes code after Thread.sleep() and can be cancelled only if it's sleeping I use Java8, I have a subclass of Thread called DelayedThread which wraps a Runnable and executes the Runnable after certain amount of time. It has a method called cancelOnlyIfStillSleeping() which interrupts Thread.sleep but I don't want to interrupt it once Runnable has been called because I'm afraid of interrupting Runnable which might react to the interruption in an unexpected way. The code looks like this:
class DelayedThread extends Thread {

    private final long delay;
    private final Runnable task;
    private boolean starting;

    private final Object lock = new Object();

    DelayedThread(long delay, Runnable task) {
        this.delay = delay;
        this.task = task;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(delay);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return;
        }

        synchronized (lock) {
            if (isInterrupted()) {
                return;
            }
            starting = true;
        }

        task.run();
    }

    /**
     * Interrupts this thread only if it's still sleeping. Once it finished sleeping
     * the thread won't get interrupted.
     */
    void cancelOnlyIfStillSleeping() {
        synchronized (lock) {
            if (starting) {
                return;
            }
            interrupt();
        }
    }
}

Does this code look safe? Isn't there any race condition where my code doesn't work as intended? Or is there any way better to achieve this?
I haven't analysed your code in detail, but it looks threadsafe on a quick scan.
I'd just suggest that you avoid reinventing the wheel. The java.util.Timer class will, I think, fit your use-case and is clearer that you are cancelling rather than interrupting your scheduled task. I think we can be fairly confident that it has been well-enough designed, implemented and reviewed to be threadsafe ...