the_prole the_prole - 27 days ago 11
Java Question

How to abstract a line of code into a variable

I want to run a line of a code in another method. Specifically, I would like to take a line of code x and run it in a new thread.

Here is my pseudo-code

LineOfCode line;
...
new NewThread(line).run()


Here is pseudo-code for
NewThread
class

public class NewThread {

LineOfCode line;

NewThread(LineOfCode line){
this.line = line;
}

public void run(){

Thread thread = new Thread() {
@Override
public void run() {

line.execute();
}
};

thread.start();
}
}


How do I abstract a line of code into a variable?

Probably a stupid question, but can't think of obvious solution.

Answer

In Java 8+, you would be able to use a lambda expression:

Runnable line = () -> { System.out.println("I am doing something"); };

(Thanks to JoopEggen for providing this in a comment).

In prior versions, you'd need to create a Runnable explicitly:

Runnable line = new Runnable() {
  @Override public void run() {
    System.out.println("I am doing something");
  }
};

You can pass this to your MyThread, and just call the run() method.

Actually, you don't need MyThread at all: you can simply do:

new Thread(line).start();

and it runs the Runnable: this is the preferred way of creating new Threads (rather than subclassing directly).

Comments