2013-10-21 2 views
-1

아래 코드를 참조하십시오. 이 오라클 튜토리얼 페이지에서 수정 된 코드 예제입니다 :자바 스레드 우선 순위

public class BadThreads { 
    static String message; 

private static class CorrectorThread extends Thread { 
    public void run() { 
     try { 
      sleep(1000); 
     } catch (InterruptedException e) {} 
     message = "Mares do eat oats."; 
     System.out.println("1: "+ message); 
    }  
} 

public static void main(String args[]) throws InterruptedException { 

    CorrectorThread c=new CorrectorThread(); 

    c.start(); 
    System.out.println("0: "+ message); 
    c.run(); 
    System.out.println("2: "+ message); 

    message = "Mares do not eat oats."; 
    System.out.println("3: "+ message); 

    Thread.sleep(2000); 
    System.out.println("4: "+ message); 
} 
} 

인쇄

0: null 
1: Mares do eat oats. 
1: Mares do eat oats. 
2: Mares do eat oats. 
3: Mares do not eat oats. 
4: Mares do not eat oats. 

하고 괜찮습니다.

내가 주요 방법

c.run(); 

을 주석, 내가 얻을

0: null 
2: null 
3: Mares do not eat oats. 
1: Mares do eat oats. 
4: Mares do eat oats. 

메인C 전에 실행되어 온 방법은? 스레드 c은 "부모"스레드와 동일한 우선 순위를 갖습니다. .

그것은 주요C 볼 수 있으며, 따라서 C주요가 반환 할 기다리고 있음인가? 이것은 이해가되지 않지만 내가 생각할 수있는 유일한 것입니다.

// ============================

편집 : 와

c.run(); 

교체

c.join(); 

동일한 효과와 미세한 프로그래밍.

+0

http://arashmd.blogspot.com/2013/06/java-threading.html#synctr –

+1

우선 순위는 힌트 일 뿐이며 대부분의 경우 '루트'또는 '관리자'가 아닌 경우 완전히 무시됩니다. CPU 사용률이 높으면 그렇게하는 것이 좋습니다. –

+0

Peter Lawrey : 공정성은 한 가지 이유로 기아를 피할 수 있다는 것을 알고 있습니다. 가장 긴 대기 스레드를 보장하지는 않지만 첫 번째 턴에서는 보장하지 않지만 높은 CPU 사용률은 들리지 않습니다. ( – Roam

답변

1

c.run()을 호출하면 실행 기능이 실행되고 완료 될 때까지 대기합니다. 대기는 또한 스레드 시간을 평행하게 다루며 첫 번째 경우에는 두 개의 양의 출력을 보게됩니다. 두 번째 경우에는 스레드가 시작되고 주 프로그램이 실행 기능과 평행으로 실행됩니다. 실행은 절전 모드이고 주 표시 명령문을 포함합니다.

c.start() 스레드가 메인에 평행하게 실행됩니다. c.run()은 실행 함수를 호출하고 완료시 다음 명령문으로 이동합니다.

+0

예, 그렇습니다. 이 시간대에 그 타이밍 차이를 놓쳤습니다. 고마워. – Roam

+0

@ 그레이 - 편집하기 전에 그의 답변이 잘 보 였습니다. thats 괜찮아/당신 물론. – Roam

+0

@roam은 여전히 ​​회색에 감사합니다 ........ –

0

CorrectorThread c=new CorrectorThread(); 

c.start(); // new thread started, but up to scheduler to decide when to give it a slice of time 
System.out.println("0: "+ message); 
c.run(); // ran in main thread 
System.out.println("2: "+ message); // as expected, message was set by the other thread 

message = "Mares do not eat oats."; 
System.out.println("3: "+ message); // as expected 

Thread.sleep(2000); 
System.out.println("4: "+ message); // as expected 

c.start()c.run() 모두가 CorrectorThread#run()를 호출 결국하지만 서로 다른 스레드에있을 것입니다 인라인 주석을 참조하십시오. 가장 먼저 도착할 스케줄러는 Thread입니다. 당신이 c.run() 스케줄러를 호출하지 않는 예에서

은 다른 스레드가 message를 초기화하는 시간이되기 전에

System.out.println("0: "+ message); // null 

System.out.println("2: "+ message); // null 

를 호출하는 시간을 가지고있다.

+0

Q를주의 깊게 읽으십시오. – Roam

+0

@ Roam 그것은 경주입니다. 한 개의 Thread는'message'를 설정하고, 다른 하나는 그것을 다시 설정합니다. –

+0

귀하의 답변이 변경되었습니다. 나는 이미 논평했다 - 원래 것. – Roam

4

스레드의 전체 지점은 병렬로 실행됩니다. 따라서 메인 스레드는 수정 자 스레드와 병렬로 실행됩니다. 그리고 교정자 스레드가 수행하는 첫 번째 작업은 1 초 동안 잠자기 상태이기 때문에 주 스레드는 수정 자 스레드가 메시지를 변경하기 전에 지침을 실행할 충분한 시간을 가지고 있습니다.

+0

예, 시차입니다. 내가 zeeshan mughal에 대해 썼던 말과 똑같다. – Roam

+0

호기심이 왜 당신이 다른 답변을 선택했는지 그리고 이보다 훨씬 더 가난하게 쓰여진 @Roam. – Gray

0

이 같은 시도 : - 메인 스레드에 대한 어떠한 보증 스레드/메소드를 호출 순서의 첫 번째 또는 두 번째를 변경할 수 없기를 간다 있기 때문에

public class BadThreads { 
    static String message; 

    private static class CorrectorThread extends Thread { 
     public void run() { 
      try { 
       sleep(1000); 
      } catch (InterruptedException e) {} 
      message = "Mares do eat oats."; 
      System.out.println("3: "+ message); 
     }  
    } 

    public static void main(String args[]) throws InterruptedException { 

     CorrectorThread c=new CorrectorThread(); 
     c.start(); 

     System.out.println("0: "+ message); 
     System.out.println("1: "+ message); 

     message = "Mares do not eat oats."; 
     System.out.println("2: "+ message); 

     Thread.sleep(2000); 
     System.out.println("4: "+ message); 
    } 
} 
+0

캔트 시작하지 않고 실행합니다. – Roam

+0

업데이트 됨, 동일 함 시도하십시오 –

+0

다른 사람들이 배울 수 있도록 설명해 주시겠습니까? 주석 처리되지 않은 코드를 삭제하면 아무 것도 가르치지 않습니다. – Gray

1

이 여기에 이상한 아무것도 친구가 없습니다.

첫 번째 c.start()은 (는) 새로운 스레드를 시작합니다. 두 번째 상황에서, 메인 쓰레드에 의해 더 호출 run()가 없다, 그래서 메인 스레드 나쁜 스레드가하는 것처럼 1 초 동안 잠을, 그냥하지 않는 동안 그렇게 첫 번째 상황에서,이

0000->thread main starts the bad thread | bad thread sleeps for 1 second 
     and prints the message value(null) 
0001->thread main runs the run() method | bad thread still is sleeping 
     with its thread 
0002-> both thread are sleeping .... 
0003->..... 
1000->either bad thread or main thread changes the message value to "Mares do eat oats." (not sure which goes first!) 
1001->thread main prints("1:" +message) | bad thread prints("1:" +message) 
1002->thread main prints("1:" +message) | bad thread has terminated X 
1003->thread main changes the message value to "Mares do not eat oats." 
1004->main threads prints the message again and sleeps for 2 seconds 
2004->main thread prints the message again. 

같은 뭔가를 메시지를 인쇄하고 값을 "Mares는 귀리를 먹지 않습니다."로 변경하려고 시도합니다. 다시 인쇄하고 2 초 동안 대기 한 다음 1 초 후에 잘못된 스레드가 깨어 난 후에 (주 스레드가 절전 상태에있는 동안) 메시지의 값을 변경하고 인쇄합니다. 2 초 후에 주 스레드가 메시지를 인쇄합니다. 잘못된 스레드에 의해 변경되는 메시지

대답은 여기에 있습니다. 실행 순서 때문에 첫 번째 또는 두 번째 스레드에 대한 보증이 없습니다. this tutorial 당신을 도울 수 있습니다.