-2

In the following code I create a callable which creates a Runnable inside the call()-method. My problem is that run()-method is never reached (code does not get executed). Do you know why and how to fix that?

public static void main(String[] args) {

    Callable<Object> c = new Callable<Object>() {

        @Override
        public Object call() throws Exception {

            Runnable r = new Runnable() {

                @Override
                public void run() {
                    System.out.println("hi");

                }
            };

            return null;
        }
    };

    try {
        c.call();
    } catch (Exception e) {

    }
}
Philip94
  • 17
  • 6

2 Answers2

0
Callable<Object> c = new Callable<Object>() {

            @Override
            public Object call() throws Exception {

                Runnable r = new Runnable() {

                    @Override
                    public void run() {
                        System.out.println("hi");

                    }
                };
                r.run();
                return null;
            }
        };
        try {
            c.call();

        } catch (Exception e) {

        }
sam
  • 27
  • 7
  • You could improve this answer by including some text that explains how your example is different from the OP's example. – Solomon Slow Mar 02 '17 at 13:37
0

Do you know why...

Already explained by others: You have written code that creates a Runnable instance, but your code does not do anything with the instance after creating it. Your code does not directly call the run() method, nor does your code hand the instance off to any other object that would call the method.

...and how to fix that?

That would depend on what you want the code to do. There are simpler ways to write a program that prints "hi" if that's all you want.

It looks as if you are trying to learn something, but you haven't told us what you want to learn.

Solomon Slow
  • 25,130
  • 5
  • 37
  • 57