为什么多线程Java代码表现得像单线程?

时间:2015-01-26 16:02:29

标签: java multithreading synchronization

我希望在第一行打印出以下代码:初始值。

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

因为我希望在主要之后完成衍生线程。但是,它打印出最后一行:来自runnable anonymous。

为什么?

1 个答案:

答案 0 :(得分:4)

Runnable.run()无法启动新主题。这是一个普通的方法调用,就像任何其他对象一样。您需要调用Thread.start()方法来创建新的线程。

而不是r8.run();你需要写

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

r.run();使用相同:

Thread t2 = new Thread (r);
t2.start();