2017-12-01 1 views
0

간단한 멀티 스레드 로봇을 만들려고합니다. 헤드는 실과 두 개의 다리, 한 개의 다리는 하나의 실로되어있다. 모든 것이 잘 작동하지만, 각 다리를 제어하기 위해 제어 스레드를 만드는 방법은 무엇입니까?스레드를 생성하여 다른 스레드를 제어하는 ​​방법은 무엇입니까?

내 코드는 다음과 같습니다

public class ClientInterface { 
public static void main(String [] args) { 
     new Controller().execute(); 
    } 
} 

내가 다른 스레드를 대기 위해 join()을 사용한다는 것을 알고

public class Controller implements CommandInterface{ 
    private final Object monitor = new Object(); 
    private int numOfSteps = 10; 

class Legs implements Runnable { 
    private final String whichLeg; 

    Legs(String whichLeg) { 
     this.whichLeg = whichLeg; 
    } 

    @Override 
    public void run() { 
     for(int i = 0; i < numOfSteps;i++) { 
      synchronized (monitor) { 
       step(); 
       try { 
        TimeUnit.SECONDS.sleep(1); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
       monitor.notify(); 
       try { 
        monitor.wait(); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
    } 

    private void step() { 
     System.out.println(whichLeg); 
    } 
} 

    Legs left = new Legs("left feet"); 
    Legs right = new Legs("right feet"); 

    @Override 
    public void execute() { 
     new Thread(left).start(); 
     new Thread(right).start(); 

    } 

} 

내가이 클래스를 사용 로봇을 시작합니다. 나는이 같은 결과를보고 싶어 : 나는 주요 방법에 머리 스레드를 생성하고 join() 전화를 시도

Init head head sends make 1 step left feet head sends make 2 step right feet and so on...

하지만, 현재의 thread 기다려야하지만 난 legs.i 같은 머리 스레드를 만들려고 기다릴 필요 Thread head = new Thread(new Runnable{ tried here to run execute method });하지만 모두 작동하지 않습니다.

답변

1

가능한 옵션은 다양합니다. 다음 중 하나가 있습니다.
각 다리는 모니터 자체가됩니다. 헤드 스레드가 시작되면 다리를 알리거나 기다립니다. 따라서 첫 번째 반복에서 헤드는 첫 번째 다리를 알리거나 기다립니다. 두 번째 반복에서 두 번째 다리를 알리거나 기다릴 것입니다. 끝까지 계속 반복합니다. 다리는 머리 스레드에 의해 통지되기를 기다리고 영원히 반복됩니다. 그들의 임무는 통보를 받고, 적절한 메시지를 인쇄하고, 머리에 통보를 보내는 것입니다. 또한 공유 CountDownLatch을 만드는 것을 고려해볼 수 있습니다

interface CommandInterface { 
    void execute(); 
} 

class Controller implements CommandInterface { 

    private static final int NUM_OF_STEPS = 10; 

    private final Legs[] legs = { 
     new Legs("left feet"), 
     new Legs("right feet") 
    }; 

    @Override 
    public void execute() { 
     Executors.newSingleThreadExecutor().execute(() -> { 
      System.out.println("Init head"); 

      for (Legs leg : legs) { 
       leg.start(); 
      } 

      for (int i = 0; i < NUM_OF_STEPS; i++) { 
       try { 
        TimeUnit.SECONDS.sleep(1); 

        int currentLegIndex = i % legs.length; 
        synchronized (legs[currentLegIndex]) { 
         System.out.println("head sends make " + (i + 1) + " step"); 
         legs[currentLegIndex].notify(); 
         legs[currentLegIndex].wait(); 
        } 
       } catch (InterruptedException e) { 
        throw new RuntimeException("Interrupted!", e); 
       } 
      } 
     }); 

    } 

    class Legs extends Thread { 
     private final String whichLeg; 

     Legs(String whichLeg) { 
      this.whichLeg = whichLeg; 
     } 

     @Override 
     public void run() { 
      while (true) { 
       try { 
        synchronized (this) { 
         this.wait(); 
         step(); 
         this.notify(); 
        } 
       } catch (InterruptedException e) { 
        throw new RuntimeException("Interrupted!", e); 
       } 
      } 
     } 

     private void step() { 
      System.out.println(whichLeg); 
     } 
    } 
} 

class ClientInterface { 
    public static void main(String [] args) { 
     new Controller().execute(); 
    } 
} 

:
여기 스케치입니다. 내가 certanly 그 javadoc을 읽는 것이 좋습니다 것입니다. 나는 당신이 아이디어를 이해하고 너 자신에 의하여 더 우아한 해결책을 창조 할 것이라는 점을 생각한다;)