0

I would expect the following code to print out on the first line: initial value.

public class RunnableLambda {

    static String accessedByThreads = "initial value";

    public static void main(String... args) {
        Runnable r8 = () -> {
            try {
                Thread.currentThread().sleep(30);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("r8");
            accessedByThreads = "from runnable lambda";
        };
        r8.run();
        Runnable r = new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.currentThread().sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("r");
                    accessedByThreads = "from runnable anonymous";
                }
            };
        r.run();
        System.out.println("Main");
        System.out.println(accessedByThreads);
    }
}

Because I would expect spawned threads to finish after the main. However, it prints out on the last line: from runnable anonymous.

Why?

5gon12eder
  • 24,280
  • 5
  • 45
  • 92
Dan
  • 11,077
  • 20
  • 84
  • 119

1 Answers1

4

Runnable.run() does not start a new Thread. It is a normal method call like on any other object. You need to call the Thread.start() method to create a new Thread.

Instead of r8.run(); you need to write

Thread t1 = new Thread (r8);
t1.start(); //this creates and runs the new thread in parallel

Same for r.run(); use:

Thread t2 = new Thread (r);
t2.start();
Simulant
  • 19,190
  • 8
  • 63
  • 98