繁体   English   中英

为什么多线程Java代码的行为类似于单线程?

[英]Why is multi-threaded Java code behaving like single-threaded?

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

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.run()不会启动新线程。 像在其他任何对象上一样,这是一个普通的方法调用。 您需要调用Thread.start()方法来创建新的线程。

代替r8.run(); 你需要写

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

r.run();相同r.run(); 采用:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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