2

How can I do this in java without using the Runnable class or implementing my threaded code in a run() method?

public void dud()
{
   System.out.println("create me on a new thread");
}

public void main() 
{
   Thread t1 = new Thread(dud).start();
   Thread t2 = new Thread(dud).start();
}
Athari
  • 33,702
  • 16
  • 105
  • 146
genxgeek
  • 13,109
  • 38
  • 135
  • 217

2 Answers2

5

Since Java 8, you can use a Lambda:

public void main ()
{
    // direct way
    new Thread(() -> dud()).start();
    // indirect way
    Thread t = new Thread(() -> dud());
    t.start();
}

Before Java 8, on Java 7, you need to use an anonymus inner class:

public void main ()
{
    // direct way
    new Thread(new Runnable() { public void run() { dud(); } }).start();
    // indirect way
    Thread t = new Thread(new Runnable() { public void run () { dud(); } });
    t.start();
}
msrd0
  • 7,816
  • 9
  • 47
  • 82
3

I think you might be able to do it implicitly if you take advantage of Java 8 features :

public class ThreadTest 
{
    public static void dud()
    {
        System.out.println("create me on a new thread");
    }

    public static void main(String[] args) 
    {
       Thread t1 = new Thread(()->dud()).start();

       // it might even work with a method reference :
       Thread t2 = new Thread(ThreadTest::dud).start();
    }

}

You are basically declaring a Runnable implicitly with a lambda expression. Of course you'll need to either change dud() to be static or create an instance before invoking it.

Eran
  • 387,369
  • 54
  • 702
  • 768