Threads Spiel gol

Hallo,
ich habe eine Frage. Beim ausführen des Programms, entsteht ein Standbild vom Spiel. Normalerweise sollte sich die neue Generation der Zellen aktualisieren also es soll ein Wachstum entstehen. Warum bewegt sich das Bild beim ausführen nicht?




public class Application {

/* Size of the playground in X dimension */
public static final int DIM_X = 200;

/* Size of the playground in Y dimension */

public static final int DIM_Y = 200;

/* Probability threshold that a cell is initially being created */
public static final float ALIVE_PROBABILITY = 0.3125f;

/* Sleep time between every generation in milliseconds */
public static final int SLEEP = 200;

/**
* Creates an potentially unlimited stream of Cell objects. The stream uses
* random numbers between [0, 1] and the probability threshold whether a
* cell is created DEAD (random > p) or ALIVE (random <= p).
*
* @param p Cell alive probability threshold.
* @Return
*/
private static Stream<Cell> createCellStream(float p) {

Random random = new Random();
return Stream.generate(() -> {
int status = random.nextFloat() <= p ? Cell.ALIVE : Cell.DEAD;
return new Cell(status);
});
}


public static void main(String[] args) {
Stream<Cell> cellStream = createCellStream(ALIVE_PROBABILITY);
Playground playground = new Playground(DIM_X, DIM_Y, cellStream);

// Create and show the application window
ApplicationFrame window = new ApplicationFrame();
window.setVisible(true);
window.getContentPane().add(new PlaygroundComponent(playground));

// Create and start a LifeThreadPool with 50 threads
LifeThreadPool pool = new LifeThreadPool(50);
pool.start();

while (true) {
Life life = new Life(playground);
for (int xi = 0; xi < DIM_X; xi++) {
for (int yi = 0; yi < DIM_Y; yi++) {

int finalXi = xi;
int finalYi = yi;

// Submit new life.process() call as runnable to the pool
pool.submit(() -> life.process(playground.getCell(finalXi, finalYi), finalXi, finalYi));
}
}

// Wait for all threads to finish this generation
try {
pool.barrier();
} catch (InterruptedException ex) {
Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
}

// Submit switch to next generation for each cell and force a
// window repaint to update the graphics
pool.submit(() -> {
playground.asList().forEach(cell -> cell.nextGen());
window.repaint();
});

// Wait SLEEP milliseconds until the next generation
try {
Thread.sleep(SLEEP);
} catch (InterruptedException ex) {
Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}






public class LifeThread extends Thread {

private final LifeThreadPool pool;
private boolean isInterrupted = false;

public LifeThread(LifeThreadPool pool) {
this.pool = pool;
}

/**
* Sets the interrupted flag, so that this thread stops after finishing
* the current task.
*/
@Override
public void interrupt() {
isInterrupted = true;
}

@Override

public void run() {
while (!isInterrupted) {
try {
// Holt die nächste Aufgabe aus dem TaskThreadPool und führt sie aus
Runnable task = pool.nextTask();
task.run();
} catch (InterruptedException e) {
// Unterbricht die weitere Ausführung des Threads bei einer InterruptedException
break;
}
}
}
}




public class LifeThreadPool {
private final Queue<Runnable> tasks = new LinkedList<>();
private final int numThreads;
private final LifeThread[] threads;

public LifeThreadPool(int numThreads) {
this.numThreads = numThreads;
this.threads = new LifeThread[numThreads];
}

public synchronized void barrier() throws InterruptedException {
while (!tasks.isEmpty()) {
wait();
}
}

public synchronized void interrupt() {
for (LifeThread thread : threads) {
thread.interrupt();
}
}

public synchronized void joinAndExit() throws InterruptedException {
barrier();
interrupt();
}

public synchronized void submit(Runnable task) {
tasks.offer(task);
notifyAll();
}

public synchronized Runnable nextTask() throws InterruptedException {
while (tasks.isEmpty()) {
wait();
}
return tasks.poll();
}

public void start() {
for (int i = 0; i < numThreads; i++) {
threads = new LifeThread(this);
threads.start();
}
}
}
 
Nutz bitte die Code Tags.

Wie sieht denn die Playground Klasse aus?

Hast du da eine Terminal operation auf den Cell Stream? Streams sind lazy, heisst sie werden erst ausgeführt wenn eine Terminal operation ausgeführt wurde. zb .collect()
 
Java:
package de.hawhamburg.inf.gol;

import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;

/**
 * Main application class.
 *
 */
public class Application {

    /* Size of the playground in X dimension */
    public static final int DIM_X = 200;
    
    /* Size of the playground in Y dimension */
    
    public static final int DIM_Y = 200;
    
    /* Probability threshold that a cell is initially being created */
    public static final float ALIVE_PROBABILITY = 0.3125f;
    
    /* Sleep time between every generation in milliseconds */
    public static final int SLEEP = 200;
    
    /**
     * Creates an potentially unlimited stream of Cell objects. The stream uses
     * random numbers between [0, 1] and the probability threshold whether a
     * cell is created DEAD (random > p) or ALIVE (random <= p).
     *
     * @param p Cell alive probability threshold.
     * @return
     */
    private static Stream<Cell> createCellStream(float p) {

Random random = new Random();
    return Stream.generate(() -> {
        int status = random.nextFloat() <= p ? Cell.ALIVE : Cell.DEAD;
        return new Cell(status);
    });
    }
    
    
    public static void main(String[] args) {
        Stream<Cell> cellStream = createCellStream(ALIVE_PROBABILITY);
        Playground playground = new Playground(DIM_X, DIM_Y, cellStream);
        
        // Create and show the application window
        ApplicationFrame window = new ApplicationFrame();
        window.setVisible(true);
        window.getContentPane().add(new PlaygroundComponent(playground));
        
        // Create and start a LifeThreadPool with 50 threads
        LifeThreadPool pool = new LifeThreadPool(50);
        pool.start();
        
       while (true) {
    Life life = new Life(playground);
    for (int xi = 0; xi < DIM_X; xi++) {
        for (int yi = 0; yi < DIM_Y; yi++) {
    
                int finalXi = xi;
                int finalYi = yi;
                
                // Submit new life.process() call as runnable to the pool
                pool.submit(() -> life.process(playground.getCell(finalXi, finalYi), finalXi, finalYi));
            }
        }

        // Wait for all threads to finish this generation
        try {
            pool.barrier();
        } catch (InterruptedException ex) {
            Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        // Submit switch to next generation for each cell and force a
        // window repaint to update the graphics
        pool.submit(() -> {
            playground.asList().forEach(cell -> cell.nextGen());
            window.repaint();
        });
        
        // Wait SLEEP milliseconds until the next generation
        try {
            Thread.sleep(SLEEP);
        } catch (InterruptedException ex) {
            Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
}
Java:
package de.hawhamburg.inf.gol;

import javax.swing.JFrame;

/**
 * Application frame showing the PlaygroundComponent with the Playground graphics.
 *
 */
public class ApplicationFrame extends JFrame {
    
    public ApplicationFrame() {
        setTitle("Game of Life");
        setSize(700, 700);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
Java:
package de.hawhamburg.inf.gol;

/**
 * Cell living on the screen.
 *
 */
public class Cell {
    
    public static final byte DEAD = (byte)0;
    public static final byte ALIVE = (byte)1;
    
    /* Current state of this cell, can be DEAD or ALIVE */
    private byte value = DEAD;
    
    /* Calculate state of the next generation */
    private byte valueNext = DEAD;
    
    public Cell(int value) {
        this.value = (byte)value;
    }
    
    public byte getValue() {
        return value;
    }
    
    /**
     * Returns true if this cell is considered to be alive.
     * @return true if cell is alive, false if cell is dead.
     */
    public boolean isAlive() {
        return value != 0;
    }
    
    /** Sets the state for this cell in the next generation.
     * @param value New state of this cell, can be DEAD or ALIVE.
      */
    public void setValueNext(byte value) {
        this.valueNext = value;
    }
    
    /** Make the next generation the current generation */
    public void nextGen() {
        this.value = this.valueNext;
    }
}
Java:
package de.hawhamburg.inf.gol;

/**
 * Includes the Game of Life rules.
 *
 */
public class Life {
    
    private final Playground playground;
    
    public Life(Playground playground) {
        this.playground = playground;
    }
    
    /**
     * Counts the ALIVE neighbours for a cell identified by playground
     * coordinates.
     *
     * @param x
     * @param y
     * @return Number of ALIVE neighbours
     */
    private int countNeighbours(int x, int y) {
        int neighbours = 0;
        for (int xi = x - 1; xi <= x + 1; xi++) {
            for (int yi = y - 1; yi <= y + 1; yi++) {
                if (x == xi && y == yi)
                    continue; // Identity
                if (playground.getCell(xi, yi).isAlive()) {
                    neighbours++;
                }
            }
        }
        return neighbours;
    }
    
    /**
     * Applies the rules of the Game of Life and sets new state of the given
     * cell. If a cell has 3 neighbours and is currently DEAD, it is revived in
     * the next generation. If a cell has less than 2 or more than 3 neightbours
     * it will die in the next generation. So if a cell has 2 or 3 neighbours
     * and is currently ALIVE it will stay ALIVE.
     * @param cell
     * @param x
     * @param y
     */
    public void process(Cell cell, int x, int y) {
        int neighbours = countNeighbours(x, y);
        
        if (neighbours == 3 && !cell.isAlive()) {
            // Cell is reborn
            cell.setValueNext(Cell.ALIVE);
        } else if (neighbours < 2 || neighbours > 3) {
            // Cell will die from loneliness or too much neighbours
            cell.setValueNext(Cell.DEAD);
        } else if (cell.isAlive()) /* 2 or 3 */ {
            // Cell stays alive
            cell.setValueNext(Cell.ALIVE);
        }
    }
}
Java:
package de.hawhamburg.inf.gol;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Interruptible Thread that receives its next tasks from a LifeThreadPool.
 *
 */
public class LifeThread extends Thread {
    
    private final LifeThreadPool pool;
    private boolean isInterrupted = false;
    
    public LifeThread(LifeThreadPool pool) {
        this.pool = pool;
    }
    
    /**
     * Sets the interrupted flag, so that this thread stops after finishing
     * the current task.
     */
    @Override
    public void interrupt() {
        isInterrupted = true;
    }
    
    @Override

public void run() {
    while (!isInterrupted()) {
        try {
            // Holt die nächste Aufgabe aus dem TaskThreadPool und führt sie aus
            Runnable task = pool.nextTask();
            task.run();
        } catch (InterruptedException e) {
            // Unterbricht die weitere Ausführung des Threads bei einer InterruptedException
            interrupt();
            break;
        }
    }
}

}
Code:
package de.hawhamburg.inf.gol;

import java.util.LinkedList;
import java.util.Queue;

public class LifeThreadPool {
    private final Queue<Runnable> tasks = new LinkedList<>();
    private final int numThreads;
    private final LifeThread[] threads;

    public LifeThreadPool(int numThreads) {
        this.numThreads = numThreads;
        this.threads = new LifeThread[numThreads];
    }

    public synchronized void barrier() throws InterruptedException {
        while (!tasks.isEmpty()) {
            wait();
        }
    }

    public synchronized void interrupt() {
        for (LifeThread thread : threads) {
            thread.interrupt();
        }
    }

    public synchronized void joinAndExit() throws InterruptedException {
        barrier();
        interrupt();
    }

    public synchronized void submit(Runnable task) {
        tasks.offer(task);
        notifyAll();
    }

    public synchronized Runnable nextTask() throws InterruptedException {
        while (tasks.isEmpty()) {
            wait();
        }
        return tasks.poll();
    }

    public void start() {
        for (int i = 0; i < numThreads; i++) {
            threads[i] = new LifeThread(this);
            threads[i].start();
        }
    }
}
Java:
package de.hawhamburg.inf.gol;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

/**
 * Playground of the Game of Life. Consists logically of a two dimensional
 * array of Cell elements (DIM_X x DIM_Y).
 *
 * @author Christian Lins
 */
public class Playground {
    
    private final int dimX;
    private final int dimY;
    
    /**
     * The actual playground. Note that we use a 1D array here although the
     * playground is 2D.
     */
    private final Cell[] playground;
    
    public Playground(int dimX, int dimY, Stream<Cell> generator) {
        this.dimX = dimX;
        this.dimY = dimY;
        
        // Initialize playground with (probably) random cells
        playground = generator.limit(dimX * dimY).toArray(Cell[]::new);
    }
    
    /**
     * Returns the Cell at the given index.
     *
     * @param x
     * @param y
     * @return Cell object
     */
    public Cell getCell(int x, int y) {
        if (x < 0 || x >= dimX || y < 0 || y >= dimY) {
            return new Cell(Cell.DEAD);
        }

        return this.playground[x * dimX + y];
    }
    
    public int getDimensionX() {
        return dimX;
    }
    
    public int getDimensionY() {
        return dimY;
    }
    
    /**
     * Returns the playground as List of Cells for easier processing the
     * Streams.
     * @return
     */
    public List<Cell> asList() {
        return Arrays.asList(playground);
    }
}
Java:
package de.hawhamburg.inf.gol;

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;

/**
 * Swing Component that draws a Playground on the screen.
 *
 */
public class PlaygroundComponent extends JComponent {

    private final Playground playground;
    
    public PlaygroundComponent(Playground playground) {
        this.playground = playground;
    }
    
    private int cellSize() {
        return Math.min(
                cellSize(playground.getDimensionX(), getWidth()),
                cellSize(playground.getDimensionX(), getHeight()));
    }
    
    private int cellSize(int playgroundDim, int componentDim) {
        int size = componentDim / playgroundDim;
        return size == 0 ? 1 : size;
    }
    
    private int offset(int cellSize, int playgroundDim, int componentDim) {
        return (componentDim - playgroundDim * cellSize) / 2;
    }
    
    /**
     * Paints the playground according to its Cell states.
     * @param g
     */
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        
        int cellSize = cellSize();
        int offX = offset(cellSize, playground.getDimensionX(), getWidth());
        int offY = offset(cellSize, playground.getDimensionY(), getHeight());
        
        for (int x = 0; x < playground.getDimensionX(); x++) {
            for (int y = 0; y < playground.getDimensionY(); y++) {
                Cell cell = playground.getCell(x, y);
                g.setColor(cell.getValue() == 0 ? Color.BLACK : Color.GREEN);
                g.fillRect(offX + x * cellSize, offY + y * cellSize, cellSize, cellSize);
            }
        }
    }
    
}
 
leider auf anhieb nicht, meine erste Vermutung ist unzutreffend, denke das ist eher ein swing thema. Vielleicht fragst du im entsprechenden sub Forum mal nach
 
Java:
        // Wait for all threads to finish this generation
        try {
            pool.barrier();
        } catch (InterruptedException ex) {
            Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
        }

An dieser Stelle bleibt er hängen. Ohne den Aufruf von pool.barrier() läuft der Code, also muss der Fehler bei dieser Methode sein.
Hab leider noch nichts mit Threads in Java gemacht, sodass ich da nicht wirklich weiterhelfen kann.
 

Neue Themen


Zurück
Oben