Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java -The method sleep(int) is undefined for the type Thread

I'm getting an error: The method sleep(int) is undefined for the type Thread. I thought the sleep method is in the Thread class in Java.

import java.util.Random;

public class Thread implements Runnable {

    String name;
    int time;
    Random r = new Random();

    public Thread(String s){
        name = s;
        time = r.nextInt(999);
    }

    public void run() {
        try{
            System.out.printf("%s is sleeping for %d\n", name, time);
            Thread.sleep(time);
            System.out.printf("%s is done", name);
        } catch(Exception e ) {
        }
    }
}
like image 864
Nicholas Kong Avatar asked Jun 30 '26 08:06

Nicholas Kong


1 Answers

You implemented your own class called Thread and try to call sleep on it, which fails, cause sleep is undefined in your class. Your class basically shadows java's Thread class.

Call your class differently (ie. MyThread or even better MyRunnable, as noted by owlstead) or call java.lang.Thread.sleep() directly.

like image 84
soulcheck Avatar answered Jul 02 '26 21:07

soulcheck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!