THREADs

eu tenho que fazer um programminha que e o seguinte:
um “racing panel” onde eu tenho que implementar 5 objetos desse “panel” na minha aplicacao.
cada um deve representar um thread.
eu tenho uma image duke.gif que é a mesma nos 5 panels.
ao clicar em start a “race” deve comecar e no final tem que ser dada a posicao do “duke” que chegou primeiro, segundo…etc
dicas?

public class Running extends JPanel implements Runnable {

	private Image duke = null;
	private int x = 0, y = 0;
	private int dX = 3;
	private int size = 50;
	private boolean start = false;
	private static final long serialVersionUID = 1L;
	private Thread myThread = new Thread(this);

	public Running() throws InstantiationException {
		super();

		try {
			//load the ball image from the class file directory
			duke = new ImageIcon(this.getClass().getResource("duke.gif"))
					.getImage();
			initialize();
		} catch (Exception e) {
			throw new InstantiationException("Image was not found!");
		}

		myThread.start();

	}

	public synchronized void start() {
		start = true;
	}

	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		g.drawImage(duke, x, y, size, size, this);
	}

	private void animate() {
		//Code to calculate the new position of the ball
		if (start) {
			if (x < 0 || x > this.getWidth() - size) {
				dX = -dX;
			}
			x = x + dX;
		}

		this.repaint();
	}

	@Override
	public void run() {

		while (!start) {
			animate();
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private void initialize() {
		this.setSize(300, 200);
		this.setLayout(new GridBagLayout());
	}

}

Algumas:

  1. Mude o nome da sua variável start para running, fica mais claro. E o seu while fica while (running), não tem aquele ! ali.
  2. Faça o seu Duke (o Runnable) chamar algum método sincronizado de uma classe controladora quando ele chegar ao final da corrida. Nessa classe, implemente a lista que dirá quem chegou em que posição. Essa classe deve zerar a lista antes que as threads sejam disparadas;
  3. Teste depois seu programa variando as prioridades das threads, vai ser interessante.

uhm. entendi. eu ja dei uma aumentada no codigo. os thread ja funcionam.
agora tenho outro problema. tem que ter um ranking. ja fiz parte do codigo mas ta com erro.

private Image duke = null;
	private int x = 0, y = 0;
	private int size = 50;
	private boolean start = false;
	private Referee referee = null;
	public boolean finished = false;
	private Integer ranking=0;  //  @jve:decl-index=0:
	private static final long serialVersionUID = 1L;
	private Thread myThread = null; //  @jve:decl-index=0:

	public Running(Referee referee){
		super();
			//load the ball image from the class file directory
			duke = new ImageIcon(this.getClass().getResource("duke.gif"))
					.getImage();
	
			initialize();
			this.referee = referee;
	}

	public synchronized void startRace() {
		start = true;
		myThread = new Thread(this);
		myThread.start();
		
	}

	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		g.drawImage(duke, x, y, size, size, this);
		
		if(finished){
			
			g.drawString(ranking.toString(), 10, 20);
			
		}
		
		
		
		
	}

	private void animate() {
		//Code to calculate the new position of the ball
		if (start) {
			if (x > this.getWidth() - size) {
				start = false;
				}
			else{
				x = x+1;
			}
		}
		
        ranking = referee.finished();
		this.repaint();
	}

	@Override
	public void run() {

		while (start) {
			animate();
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private void initialize() {
		this.setSize(300, 200);
		this.setLayout(new GridBagLayout());
	}

}

Ajudaria se você dissesse que erro…

fiz 2 classes e uma interface.
a jframe classe que contem os panels.
a running class que é a classe extended runnable.
a referee que e a interface.

[code]
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.eclipse.ve.internal.java.vce.launcher.remotevm.JFCLauncher$1.run(JFCLauncher.java:59)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: java.lang.Error: Unresolved compilation problem:
The constructor Running() is undefined

at at.fhjoanneum.ima06.prog2.Homework7.getJPanel5(Homework7.java:137)
at at.fhjoanneum.ima06.prog2.Homework7.getJContentPane(Homework7.java:54)
at at.fhjoanneum.ima06.prog2.Homework7.initialize(Homework7.java:39)
at at.fhjoanneum.ima06.prog2.Homework7.<init>(Homework7.java:29)
... 13 more

IWAV0052E Invocation Target Exception creating at.fhjoanneum.ima06.prog2.Homework7[/code]

ok. ja dei uma concertada. coloquei a running(null).
agora da o seguinte erro…

Exception in thread "Thread-2" java.lang.NullPointerException
	at at.fhjoanneum.ima06.prog2.Running.animate(Running.java:65)
	at at.fhjoanneum.ima06.prog2.Running.run(Running.java:73)
	at java.lang.Thread.run(Unknown Source)

e isso em todos os threads. exatamente os mesmos erros

ta algum erro com o metodo run () e o animate()
:confused:
ich weiss es nicht weiter…ich weiss es nicht mehr… :cry:

private void animate() {
		
		if (start) {
			if (x > this.getWidth() - size) {
				start = false;
				}
			else{
				x = x+1;
			}
		}
		
        ranking = referee.finished();//ERRRRRROOOOOOOOOOo
		this.repaint();
	}

	@Override
	public void run() {

		while (start) {
			animate();//ERRRROOOOOO
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

os tags sao realmente bons…

ICH WEISS ES NICHT MEHR UND ICH HASSE JAVA!!!
:cry: