类实现了Runnable,但未定义start()和sleep()方法

时间:2013-06-10 14:28:36

标签: java multithreading interface sleep runnable

我创建了一个名为Thread的类,它实现了Runnable但我出于某种原因无法调用start()sleep()方法。每当我尝试这样做时,我都会收到错误,说这些方法对于类来说是未定义的,并建议我创建它们。所以我创建了一个新项目并复制了一个示例代码,以查看我自己的代码是否有问题,并且我收到了相同的错误。这是示例代码:

class Thread implements Runnable {
    private int a;
    public Thread (int a) {
        this.a = a;
    }
    public void run() {
        for (int i = 1; i <= a; ++i) {
            System.out.println(Thread.currentThread().getName() + " is " + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {}
        }
    }
}

这是我自己的代码:

public class Thread extends PID implements Runnable {
    public Thread() {};                      // Empty constructor for thread object
    public void run() {
        Random gen = new Random();           // Generates random values
        int sleepTime;                       // Sleep time
        sleepTime = gen.nextInt(60 - 1) + 1; // Generates random sleep time between 1 and 60 seconds
        try {
            Thread.sleep();
        } catch (Exception e) {
            System.out.println(e);
        } 
        System.out.println("The thread has been terminated");
    }
}

3 个答案:

答案 0 :(得分:8)

要修复当前错误,只需将Thread类重命名为MyThread(或其他),因为Thread类隐藏了java.lang.Thread类。

如果您想坚持Thread,则必须使用java.lang.Thread的完全限定名称,如下所示:

try{
    java.lang.Thread.sleep(1000);
    // ...

答案 1 :(得分:0)

<强>误

  1. 将班级名称从Thread更改为MyThread
  2. 调用run()时会调用
  3. start()。使用类对象调用start()
  4. Thread.sleep();需要一个论据,sleepTime
  5. 以下是我认为您想要做的代码。在Eclipse Juno JDK 1.7上测试

    import java.util.Random;
    
    class NewThread implements Runnable {
    
        public NewThread () {
        }
        public void run() {
            Random gen = new Random();           // Generates random values
            int sleepTime;                       // Sleep time
            sleepTime = gen.nextInt(60 - 1) + 1; // Generates random sleep time between 1 and 60 seconds
    
            try {
                Thread.sleep(sleepTime);
            } catch (Exception e) {
                System.out.println(e);
            } 
            System.out.println("The thread has been terminated");
        }
    }
    
    class MyThread {
    
        public static void main(String[] args) {
            NewThread t = new NewThread();
            Thread t1 = new Thread(t);
            t1.start();
    
        }
    }
    

    <强>输出

    线程已被终止

答案 2 :(得分:0)

接口Runnable没有方法start()和sleep(),所以要小心它。 Interface Runnable只有run()方法,Java API推荐&#34;如果您只打算覆盖run()方法而不使用其他Thread方法,则应使用Runnable接口。&#34; 请在此处查看Java API的Runnable文档:http://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html
在其他所有情况下,您的类应该扩展Thread类。