Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

multithreading - 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
", name, time);
            Thread.sleep(time);
            System.out.printf("%s is done", name);
        } catch(Exception e ) {
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.6k users

...