简体   繁体   中英

Why is multi-threaded Java code behaving like single-threaded?

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM