0
다음 코드가 첫 줄에 인쇄 될 것으로 기대합니다 : 초기 값.멀티 스레드 Java 코드가 단일 스레드처럼 작동하는 이유는 무엇입니까?
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.
왜?
어디 당신이 다른 스레드를 만들 생각하십니까? 두 개의'Runnable' 객체에 대해서'run'을 호출 중입니다 ... –
스레드를 시작하지 마십시오. Runnable에서 메소드 run()을 호출하기 만하면된다. [자바 두 개의 스레드를 시작하는 중 –
가능한 복제?] (http://stackoverflow.com/questions/27819356/java-starting-two-threads) – 5gon12eder