Search code examples
javaenumsrunnable

Implementing Runnable in Enum


I am just playing around with enum and I wanted to see how it behaves under some crazy scenarios. Well, few java nerds might know that we can actually implement a interface in Enums. So I came up with below code and wanted to know if the thread is created and called. I am curious if anyone can explain why the sysout is not printed. The below code is valid i.e compiles fine and executes. It just prints nothing. Can anyone explain clearly?

Also why values() method is not declared either in Enum class or Object class. Why the values method is provided by java compiler. Why the Sun/Oracle din't think of implementing it in Enum class.

 package com.test;


  enum MyEnum implements Runnable{

      ENUM1,ENUM2,ENUM3;
      public void run() {

          System.out.println("Inside MyEnum"+Thread.currentThread().getName());
      }
}


public class EnumTesting {

    MyEnum en;

      public static void main(String[] args) {

    EnumTesting test = new EnumTesting();

          Thread t = new Thread(test.en);
        t.start();

    }
}

Solution

  • It just prints nothing. Can anyone explain clearly?

    Note that you did not give en a value. Therefore, it is null. When null is passed to the constructor of Thread, the thread is documented to do nothing:

    Parameters:

    target - the object whose run method is invoked when this thread is started. If null, this classes run method does nothing.

    You can do this instead:

    new Thread(MyEnum.ENUM1).start();
    

    Why the Sun/Oracle din't think of implementing it in Enum class.

    My speculation is that values, if it were in Enum<T>, should be abstract, but static methods can't be abstract.