How to make another sleep thread in Java

I have a class that extends Thread. This thread at startup spends most of the time in sleep mode, it checks if the truth performs a simple action, and then sleep for 1/2 second and repeat.

The class also has an open method that is called by other threads. If this is called, I want the thread to sleep longer if it is already sleeping or just sleep immediately if it is not. I tried to get this.sleep, but it seems that the current thread is still sleeping, and it complains that the sleep method is static and needs to access statically.

This program shows my problem when CauseSleep is called, I want it to stop printing numbers until this dream ends.

public class Sleeper {
    public static void main(String[] args) {
        new Sleeper();
    }
    public Sleeper() {
        System.out.println("Creating T");
        T t = new T();
        System.out.println("Causing sleep");
        t.CauseSleep();
        System.out.println("Sleep caused");
    }
    public class T extends Thread {
        public T() {
            this.start();
        }
        public void run() {
            for (int i = 0; i < 30; i++) {
                System.out.println("T Thread: " + i);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                }
            }
        }
        public void CauseSleep() {
            try {
                this.sleep(2000);
            } catch (InterruptedException e) {
            }
        }
    }
}

The output I get is

Creating T
Causing sleep
T Thread: 0
T Thread: 1
T Thread: 2
T Thread: 3
T Thread: 4
T Thread: 5
T Thread: 6
T Thread: 7
T Thread: 8
T Thread: 9
T Thread: 10
T Thread: 11
T Thread: 12
T Thread: 13
T Thread: 14
T Thread: 15
T Thread: 16
T Thread: 17
T Thread: 18
Sleep caused
T Thread: 19
T Thread: 20
T Thread: 21
T Thread: 22
T Thread: 23
T Thread: 24
T Thread: 25
T Thread: 26
T Thread: 27
T Thread: 28
T Thread: 29
+5
3

. ( suspend(), , , ). :

this.sleep(200);

sleep - Thread, "this". sleep - - IDE .

, " ", - .

, . , - , , . . , - , , .

+22

:

public AtomicBoolean waitLonger = new AtomicBoolean  ();
public Object lock = new Object ();

run():

synchronized (lock) {
    if (waitLonger.get ()) {
        lock.wait ();
    }
}

:

synchronized (lock) {
try {
    sleeper.waitLonger.set(true);
    ...
    lock.notify();
    sleeper.waitLonger.set(false);
}

, , .

+3

, , , volatile. , .

, , . , . ... , , .

, , , . , , , , , , ...

+1
source

All Articles