Problem using Graphics with multiple Threads [Java]

0

I'm trying to make an application that draws me several circles in a JFrame with multiple Threads but at the time of running the program only draws 2 circles and I can not find the problem if someone could support me I leave the code below.

package juego2;

import java.awt.Color;
import java.awt.Graphics;
import java.util.Scanner;
import javax.swing.JFrame;
import java.util.Random;

public class simulacion extends JFrame implements Runnable {
    Scanner scanner = new Scanner(System.in);
    int cantidad;
    int aleatoriox,aleatorioy,aleatoriox1,aleatorioy1;

    public simulacion() {    
        System.out.println("¿# de Agentes?");
        cantidad = scanner.nextInt();
        Thread agentes[]= new Thread[cantidad];
        for(int i=0;i<cantidad;i++) {
            agentes[i] = new Thread(this);
            agentes[i].start();
            System.out.println("Hilo: "+i);
        }   
    }

    public void paint(Graphics g) {

        aleatoriox = (int) (Math.random() * 375) + 15;
        aleatorioy = (int) (Math.random() * 500) + 100;
        aleatoriox1 = (int) (Math.random() * 375) + 15;
        aleatorioy1 = (int) (Math.random() * 500) + 100;
        g.drawOval(aleatoriox,aleatorioy,aleatoriox1,aleatorioy1);

    }

    public static void main(String[] args) {
        simulacion frame = new simulacion();
        frame.setSize(400,600);
        frame.setVisible(true);
    }

    @Override
    public void run() {
        repaint();
    }
}
    
asked by Luis Daniel 08.04.2018 в 22:33
source

1 answer

0

All threads work with the same JFrame, modifying its instance variables concurrently:

int aleatoriox,aleatorioy,aleatoriox1,aleatorioy1;

Instead, you could move the thread initialization code to main , and the paint code to the run() method using local variables:

public static void main(String[] args) {
    simulacion frame = new simulacion();
    frame.setSize(1000, 800);
    frame.setVisible(true);

    System.out.println("¿# de Agentes?");
    Scanner scanner = new Scanner(System.in);
    int cantidad = scanner.nextInt();
    Thread agentes[] = new Thread[cantidad];
    for (int i = 0; i < cantidad; i++) {
        agentes[i] = new Thread(frame);
        agentes[i].start();
        System.out.println("Hilo: " + i);
    }
}

@Override
public void run() {
    Graphics g = this.getGraphics();
    int aleatoriox = (int) (Math.random() * 375) + 15;
    int aleatorioy = (int) (Math.random() * 500) + 100;
    int aleatoriox1 = (int) (Math.random() * 375) + 15;
    int aleatorioy1 = (int) (Math.random() * 500) + 100;
    g.drawOval(aleatoriox, aleatorioy, aleatoriox1, aleatorioy1);
}
    
answered by 09.04.2018 в 06:09