1 10 package org.jgap.distr; 11 12 import org.jgap.*; 13 14 25 public abstract class Breeder 26 implements Runnable { 27 28 private final static String CVS_REVISION = "$Revision: 1.11 $"; 29 30 33 private Breeder m_master; 34 35 38 private Breeder[] m_workers; 39 40 43 private Genotype m_genotype; 44 45 48 private IPopulationMerger m_populationMerger; 49 50 private transient boolean m_running; 51 52 private transient boolean m_stopped = true; 53 54 private transient MeanBuffer m_meanBuffer = new MeanBuffer(40); 55 56 public Breeder(final IPopulationMerger a_populationMerger) { 57 super(); 58 m_populationMerger = a_populationMerger; 59 } 60 61 67 public void run() { 68 try { 69 m_stopped = false; 70 while (m_running) { 71 evalOneGeneration(); 72 int sleepTime = m_meanBuffer.mean() / 100; 73 if (sleepTime <= 0) { 74 pause(1); 75 } 76 else { 77 pause(sleepTime); 78 } 79 } 80 m_stopped = true; 81 } 82 catch (Throwable t) { 83 m_stopped = true; 84 m_running = false; 85 } 89 } 90 91 99 private void evalOneGeneration() 100 throws Exception { 101 long begin = System.currentTimeMillis(); 102 m_genotype.evolve(1); 103 informParent(); 104 m_meanBuffer.add( (int) (System.currentTimeMillis() - begin)); 105 } 106 107 protected void informParent() { 108 109 } 110 111 119 private synchronized void pause(final int a_milliSec) { 120 try { 121 wait(a_milliSec); 122 } 123 catch (InterruptedException e) { 124 ; 125 } 126 } 127 128 public void start() { 129 if (!m_running) { 130 m_running = true; 131 Thread thread = new Thread (this); 132 thread.start(); 133 } 134 } 135 136 public void stop() { 137 if (m_running) { 138 m_running = false; 139 if (m_genotype != null) { 140 141 147 } 148 } 149 } 150 151 public boolean isRunning() { 152 return m_running; 153 } 154 155 public boolean canBeStarted() { 156 return !m_running; 157 } 158 159 public boolean canBeStopped() { 160 return m_running; 161 } 162 } 163 167 class MeanBuffer { 168 private int[] m_buf = null; 169 170 private int m_size; 171 172 private int m_index; 173 174 public MeanBuffer(final int a_size) { 175 m_size = a_size; 176 m_buf = new int[m_size]; 177 for (int i = 0; i < m_size; i++) { 178 m_buf[i] = 0; 179 } 180 } 181 182 public void add(final int a_val) { 183 m_buf[m_index] = a_val; 184 m_index = (m_index + 1) % m_size; 185 } 186 187 public int mean() { 188 int sum = 0; 189 for (int i = 0; i < m_size; i++) { 190 sum += m_buf[i]; 191 } 192 return sum / m_size; 193 } 194 195 public void reset() { 196 for (int i = 0; i < m_size; i++) { 197 m_buf[i] = 0; 198 } 199 } 200 } 201 | Popular Tags |