2

에서 두 개의 스레드 1-20 :인쇄 번호 나는 두 개의 스레드와 숫자 1-20를 인쇄하기 위해 노력하고있어 자바

  • 에도 실 - 인쇄 짝수 번호.
  • 이상한 스레드 - 홀수 만 인쇄하십시오.

또한 동기화를위한 잠금 개체가 있습니다.

내 응용 프로그램이 작동하지 않습니다. 문제가 무엇인지 말해 줄 수 있습니까?

내 코드 :

public class runIt 
{ 

    public static void main(String[] args) 
    { 
     Odd odd = new Odd("odd thread"); 
     Even even = new Even("even thread"); 

     odd._t.start(); 
     even._t.start(); 

     try{ 
      odd._t.join(); 
      even._t.join(); 
     } 
     catch (InterruptedException e){ 
      System.out.println(e.getMessage()); 
     } 
    } 
} 

public class Constants{ 
    static Object lock = new Object(); 
} 

public class Even implements Runnable{ 
    Thread _t; 
    String _threadName; 

    public Even(String threadName){ 
     _threadName = threadName; 
     _t = new Thread(this); 
    } 

    @Override 
    public void run(){ 
     for (int i = 0; i < 20; i++){ 
      if (i % 2 == 0){ 
       synchronized (Constants.lock){     
        try{ 
         Constants.lock.wait(); 
         Constants.lock.notifyAll(); 
        } 
        catch (InterruptedException e){ 
         e.printStackTrace(); 
        } 
        System.out.println(_threadName + " " + i + " "); 
       } 
      } 
     } 
    } 
} 

public class Odd implements Runnable{ 
    Thread _t; 
    String _threadName; 

    public Odd(String threadName){ 
     _threadName = threadName; 
     _t = new Thread(this); 

    } 

    @Override 
    public void run(){ 
     for (int i = 0; i < 20; i++){ 
      if (i % 2 == 1){ 
       synchronized (Constants.lock){     
        try{ 
         Constants.lock.wait(); 
         Constants.lock.notifyAll(); 
        } 
        catch (InterruptedException e1){ 
         e1.printStackTrace(); 
        } 
        System.out.println(_threadName + " " + i + " "); 
       } 
      } 
     } 
    } 
} 

내 출력은 다음과 같아야합니다

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 

도와 주셔서 감사합니다. Tam.

+0

은 여기를보세요 : http://stackoverflow.com/questions/6017281/odd-even-number-printing-using-thread 정확하게 필요한 것 같습니다. –

+8

그래서 나는 이것이 새로운 학기가 막 시작된 ​​곳을 의미한다고 생각하십니까? * 한숨 * – Voo

+0

즉각적인 문제는 두 스레드가 잠금 대기 상태가되어 알림이 수신되지 않는다는 것입니다.이 코드에는 몇 가지 다른 문제가 있습니다. –

답변

0

synchronized에서 사용한 물건을 기다리면서 synchronizedwait을 오용하고 있습니다. 절대 다시 쓰지 마십시오.. 사실 여기에 무슨 일이 : 당신이 wait 줄에서 Constants.lock

  • 에 대한 잠금을 얻을

    • 라인 synchronized에서, 당신은 Constants.lock에에게 잠금을 해제하고 다른 스레드에서 통지 대기 .

    그래서 음식물에 무슨 일이 일어나고 있는지 :

    • 첫 번째 스레드 (그것이 무엇인지에 상관없이) synchronized에 도달하고 두 번째
    • 첫 번째 스레드를 차단 진행은 synchonizing의 잠금을 해제하고 그 자체를 넣어 알림 대기 상태
    • 두 번째 스레드는 첫 번째로 잠금을 해제했기 때문에
    • 두 스레드가 지금까지는 발생하지 않는 알림을 기다리고 있기 때문에 두 번째 스레드는 synchronized을 통과합니다. UR
    • 사람에게 도움이 될 것입니다 코드 아래
  • 1

    ,

    public class MyClass { 
    
    private static Object lock = new Object(); 
    
    public static void main(String args[]){ 
    
        Runnable runnable1 = new Runnable() { 
         @Override 
         public void run() { 
          for(int i=1; i<20; i=i+2){ 
           synchronized (lock) { 
            System.out.println("Thread 1: "+i); 
            try { 
             lock.notifyAll(); 
             lock.wait(); 
            } catch (InterruptedException e) { 
             System.out.println("Error in Thread 1: "+e.getMessage()); 
            } 
           } 
          } 
         } 
        }; 
    
    
        Runnable runnable2 = new Runnable() { 
         @Override 
         public void run() { 
          for(int i=2; i<=20; i=i+2){ 
           synchronized (lock) { 
            System.out.println("Thread 2: "+i); 
            try { 
             lock.notifyAll(); 
             lock.wait(); 
            } catch (InterruptedException e) { 
             System.out.println("Error in Thread 2: "+e.getMessage()); 
            } 
           } 
          } 
         } 
        }; 
    
        Thread thread1 = new Thread(runnable1); 
        Thread thread2 = new Thread(runnable2); 
    
        System.out.println("Thread Start: "); 
        thread1.start(); 
        thread2.start();    
    } 
    
    }