Java - 方法sleep(int)未定义Thread类型 [英] Java -The method sleep(int) is undefined for the type Thread

查看:341
本文介绍了Java - 方法sleep(int)未定义Thread类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到错误:对于Thread类型,方法sleep(int)是未定义的。我认为sleep方法在Java中的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 ) {
        }
    }
}


推荐答案

您实现了自己的类 Thread 并尝试调用 sleep on,失败,导致 sleep 在您的课程中未定义。你的班级基本上影响了java的线程类。

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.

以不同方式调用你的类(即 MyThread 甚至更好 MyRunnable ,如owlstead所述)或致电 java.lang.Thread.sleep()直接。

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

这篇关于Java - 方法sleep(int)未定义Thread类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆