2016-06-01 6 views
0

Я делаю пример в книге и имеет пример с резьбой, в котором имитируется светофор. Я понимаю большую часть программы, однако, я смущен тем, что в книге говорится, что «отдельный поток будет запускать каждый светофор», похоже, что только один поток был создан в основном приложении? У меня есть перечисление, в котором перечислены все константы моего светофора.Threaded TrafficLightExample многочисленные потоки?

public enum TrafficLightColor { 
YELLOW,GREEN,RED 
} 

А дальше остальная часть программы.

public class TrafficLightSimulator implements Runnable { 
private Thread thread;//holds the thread that runs the simulation 
private TrafficLightColor color;//holds the traffic light color 
boolean stop=false;//set to true to stop the simulation 
boolean changed=false;//true when the light has changed 
public TrafficLightSimulator(TrafficLightColor inital){ 
color=inital; 
thread=new Thread(this); 
thread.start(); 
} 
public TrafficLightSimulator(){ 
color=TrafficLightColor.RED; 
thread=new Thread(this); 
thread.start(); 
} 
@Override 
public void run() { 
    //start up the light 
    while(!stop){ 
     try{ 
      switch(color){ 
      case GREEN: 
       Thread.sleep(10000);//green sleeps for 10 seconds 
       break; 
      case RED: 
       Thread.sleep(2000);//yellow for 2 seconds 
       break; 
      case YELLOW: 
       Thread.sleep(12000);//red for 12 seconds 
       break; 

      } 
     }catch(Exception e){ 

     } 
     changeColor(); 
    } 
} 
synchronized void changeColor(){ 
    switch(color){ 
    case RED: 
     color=TrafficLightColor.GREEN; 
     break; 
    case YELLOW:  
     color=TrafficLightColor.RED; 
     break; 
    case GREEN: 
     color=TrafficLightColor.YELLOW;  
    } 
    changed=true; 
    System.out.println("Notfiy Called We changed the light"); 
    notify(); 
} 
synchronized void waitForChange(){ 
    try{ 
     while(!changed){ 
      System.out.println("waiting for Light to change"); 
      wait(); 
     } 
     changed=false; 

    }catch(Exception e){ 

    } 
} 
synchronized TrafficLightColor getColor(){ 
    return color; 
} 
synchronized void cancel(){ 
    stop=true; 
} 

} 
class Demo{ 
public static void main(String[]args){ 
    TrafficLightSimulator t1=new  TrafficLightSimulator(TrafficLightColor.YELLOW); 
    for(int i=0;i<9;i++){ 
     System.out.println(t1.getColor()); 
     t1.waitForChange(); 
    } 
    t1.cancel(); 
} 
} 
+0

есть два потока, основной поток программы и трафик симулятор нить, может быть, в книге есть опечатка и они имели в виде * отдельный поток будет работать каждый симулятор трафика * – Gusman

+0

Почему mehtods необходимо синхронизировать hronized, если их только один поток работает на TrafficLightSimulator? – Eli

+0

Или я думаю, что другой поток является основным потоком, который связывается с потоком TrafficLightSimulator? – Eli

ответ

0

Распечатайте имя потока в каждой println команды, это показывает, какой поток выполняет какую часть кода, и это поможет вам понять, что происходит.
Просто:

System.out.println(Thread.currentThread().getName() + "==>" 
        + "Notfiy Called We changed the light"); 

Если вы запустите приложение, вы получите:

Thread-0==> start up the light 
main==>YELLOW 
main==>waiting for Light to change 
Thread-0==>Notfiy Called We changed the light 
main==>RED 
main==>waiting for Light to change 
Thread-0==>Notfiy Called We changed the light 
main==>GREEN 
main==>waiting for Light to change 
Thread-0==>Notfiy Called We changed the light 
main==>YELLOW 
main==>waiting for Light to change 
Thread-0==>Notfiy Called We changed the light 
main==>RED 
main==>waiting for Light to change 
Thread-0==>Notfiy Called We changed the light 
main==>GREEN 
main==>waiting for Light to change 
Thread-0==>Notfiy Called We changed the light 
main==>YELLOW 
main==>waiting for Light to change 
Thread-0==>Notfiy Called We changed the light 
main==>RED 
main==>waiting for Light to change 
Thread-0==>Notfiy Called We changed the light 
main==>GREEN 
main==>waiting for Light to change 
Thread-0==>Notfiy Called We changed the light 
Thread-0==>Notfiy Called We changed the light 

Существует всегда основной нить в каждом приложении Java - это поток создается с помощью виртуальной машины Java , а основной поток выполняет код приложения (вызов метода public static void main()).
Приложение может создавать и запускать другие темы - в коде это имя Thread-0 и он будет создан и запущен в конструкторе - здесь:

public TrafficLightSimulator(TrafficLightColor inital) { 
    color = inital; 
    thread = new Thread(this); // creates a new thread 
    thread.start();    // starts the new thread 
} 

Пожалуйста, копировать, вставлять и запустить этот код, он имеет Thread.currentThread().getName() + "==>" включены в каждой println команды:

public class TrafficLightSimulator implements Runnable { 

    private Thread thread;// holds the thread that runs the simulation 
    private TrafficLightColor color;// holds the traffic light color 
    boolean stop = false;// set to true to stop the simulation 
    boolean changed = false;// true when the light has changed 

    public TrafficLightSimulator(TrafficLightColor inital) { 
     color = inital; 
     thread = new Thread(this); 
     thread.start(); 
    } 

    public TrafficLightSimulator() { 
     color = TrafficLightColor.RED; 
     thread = new Thread(this); 
     thread.start(); 
    } 

    @Override 
    public void run() { 
     // start up the light 
     System.out.println(Thread.currentThread().getName() +"==>" +" start up the light"); 
     while (!stop) { 
      try { 
       switch (color) { 
       case GREEN: 
        Thread.sleep(10000);// green sleeps for 10 seconds 
        break; 
       case RED: 
        Thread.sleep(2000);// yellow for 2 seconds 
        break; 
       case YELLOW: 
        Thread.sleep(12000);// red for 12 seconds 
        break; 

       } 
      } catch (Exception e) { 

      } 
      changeColor(); 
     } 
    } 

    synchronized void changeColor() { 
     switch (color) { 
     case RED: 
      color = TrafficLightColor.GREEN; 
      break; 
     case YELLOW: 
      color = TrafficLightColor.RED; 
      break; 
     case GREEN: 
      color = TrafficLightColor.YELLOW; 
     } 
     changed = true; 
     System.out.println(Thread.currentThread().getName() + "==>" + "Notfiy Called We changed the light"); 
     notify(); 
    } 

    synchronized void waitForChange() { 
     try { 
      while (!changed) { 
       System.out.println(Thread.currentThread().getName() + "==>" + "waiting for Light to change"); 
       wait(); 
      } 
      changed = false; 

     } catch (Exception e) { 

     } 
    } 

    synchronized TrafficLightColor getColor() { 
     return color; 
    } 

    synchronized void cancel() { 
     stop = true; 
    } 

    public static void main(String[] args) { 
     TrafficLightSimulator t1 = new TrafficLightSimulator(TrafficLightColor.YELLOW); 
     for (int i = 0; i < 9; i++) { 
      System.out.println(Thread.currentThread().getName() + "==>" + t1.getColor()); 
      t1.waitForChange(); 
     } 
     t1.cancel(); 
    } 

}