Cavaleiro Cavaleiro - 9 months ago 26
Java Question

How can I count how many times Thread has been suspended

I'm making a very simple program in java, even because I'm a student. I made a program that count 1 at 1000, and when the number is multiple for 2 the thread is suspended for about 500ms. That's ok. But in the final, I need to show how many times the thread has been suspended. Like

System.out.println("The thread has been suspended for: " );


I have no idea. I appreciate any help.

@Override
public void run () {
for (int i = 0; i < 1000; i++) {
if (i % 2 == 0) {
try {
System.out.println(i);
Thread.sleep(500);

} catch (InterruptedException ex) {
Logger.getLogger(ThreadNumeros.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
System.out.println("thread has been suspended for: ");
}

Answer Source

TRY LIKE THIS-:

@Override
public void run() {
int count = 0;
    for (int i = 0; i < 1000; i++) {
        if (i % 2 == 0) {
            try {
                System.out.println(i);
                Thread.sleep(500);
                count+=1

            } catch (InterruptedException ex) {
                Logger.getLogger(ThreadNumeros.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    System.out.println("thread has been suspended for: "+count);

}