2015-01-26 2 views
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.

왜?

+5

어디 당신이 다른 스레드를 만들 생각하십니까? 두 개의'Runnable' 객체에 대해서'run'을 호출 중입니다 ... –

+1

스레드를 시작하지 마십시오. Runnable에서 메소드 run()을 호출하기 만하면된다. [자바 두 개의 스레드를 시작하는 중 –

+1

가능한 복제?] (http://stackoverflow.com/questions/27819356/java-starting-two-threads) – 5gon12eder

답변

4

Runnable.run() 새 스레드가 시작되지 않습니다. 다른 객체와 마찬가지로 일반적인 메소드 호출입니다. 새 스레드를 만들려면 Thread.start() 메서드를 호출해야합니다.

대신 r8.run();

당신은 r.run(); 사용

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

같은 작성할 필요가 :

Thread t2 = new Thread (r); 
t2.start(); 
관련 문제