1 10 package examples.simpleBooleanThreaded; 11 12 import org.jgap.*; 13 import org.jgap.impl.*; 14 import org.jgap.event.*; 15 16 23 public class SimpleExample { 24 25 private static final String CVS_REVISION = "$Revision: 1.2 $"; 26 27 36 public static void main(String [] args) 37 throws Exception { 38 final int numEvolutions = 500; 39 final int numThreads = 5; 40 int chromeSize = 20; 41 if (chromeSize > 32) { 42 System.err.println("This example does not handle " + 43 "Chromosomes greater than 32 bits in length."); 44 System.exit( -1); 45 } 46 for (int i = 0; i < numThreads; i++) { 47 final int j = i; 48 Configuration gaConf = new DefaultConfiguration(i + "", "no name"); 49 gaConf.setPreservFittestIndividual(i % 2 == 0); 50 gaConf.setKeepPopulationSizeConstant(i % 2 != 0); 51 IChromosome sampleChromosome = new Chromosome(gaConf, 52 new BooleanGene(gaConf), chromeSize); 53 gaConf.setSampleChromosome(sampleChromosome); 54 gaConf.setPopulationSize(gaConf.getRandomGenerator().nextInt(500)); 55 gaConf.setFitnessFunction(new MaxFunction()); 56 Genotype genotype = null; 57 try { 58 genotype = Genotype.randomInitialGenotype(gaConf); 59 } catch (InvalidConfigurationException e) { 60 e.printStackTrace(); 61 System.exit( -2); 62 } 63 final Thread t1 = new Thread (genotype); 64 gaConf.getEventManager().addEventListener(GeneticEvent. 65 GENOTYPE_EVOLVED_EVENT, new GeneticEventListener() { 66 public void geneticEventFired(GeneticEvent a_firedEvent) { 67 Genotype genotype = (Genotype) a_firedEvent.getSource(); 68 int evno = genotype.getConfiguration().getGenerationNr(); 69 if (evno % 10 == 0) { 70 double bestFitness = genotype.getFittestChromosome(). 71 getFitnessValue(); 72 System.out.println(t1.getName() + ": Evolving generation " + evno 73 + ", best fitness: " + bestFitness); 74 } 75 if (evno > numEvolutions) { 76 t1.stop(); 77 } 78 else { 79 try { 80 t1.sleep( (j + 1) * 3); 81 } catch (InterruptedException iex) { 82 iex.printStackTrace(); 83 System.exit(1); 84 } 85 } 86 } 87 }); 88 t1.setPriority( (i % 2) + 1); 89 t1.start(); 90 } 91 } 92 } 93 | Popular Tags |