-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) {

    }
}
2
  • 4
    You've forgotten invoke r.run();
    – Andremoniy
    Commented Mar 2, 2017 at 12:41
  • 3
    Well, you actually dont call run method
    – kamehl23
    Commented Mar 2, 2017 at 12:42

2 Answers 2

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) {

        }
1
  • You could improve this answer by including some text that explains how your example is different from the OP's example. Commented Mar 2, 2017 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.