Two threads run always in wrong order, plz help :( (graphics and music)

I have managed to make two threads.

The first thread is supposed to refresh images on screen by JPanel.

The second thread is supposed to play midi music.

In my code the second thread is established onlyafter the first thread has already succesfullyfinished.

However when running the code, I will always hear the midi sequence first as a whole and only after that the images will be updated on screen. This is annoying.I would like to graphics update emerge exactly at the same time as music begins.

Please help me, I am running out of time.

A scetch of my program:

privatestaticclass ThreadAction1implements Runnable{

publicvoid run(){

updateScreenByJPanels();

}

}

privatestaticclass ThreadAction2implements Runnable{

publicvoid run(){

playMidiMusic();

}

}

privatevoid mouseClickedOnImage(){

Thread t1 =new Thread(new ThreadAction());

t1.start();

while (t1.isAlive()){

t1.join(timeIntervalForCheckingIsThreadStillAliveMillis);

if (((System.currentTimeMillis() - startingTimeMillis) > patientWaitingTimeForThreadMillis) && t1.isAlive()){

t1.interrupt();

t1.join();

}

}

Thread t2 =new Thread(new ThreadAction2());

t2.start();

while (t2.isAlive()){

t2.join(timeIntervalForCheckingIsThreadStillAliveMillis);

if (((System.currentTimeMillis() - startingTimeMillis) > patientWaitingTimeForThreadMillis) && t2.isAlive()){

t2.interrupt();

t2.join();

}

}

}

[2854 byte] By [wonderful123a] at [2007-11-27 10:23:10]
# 1

You are making a very common Swing mistake. Event callbacks like mouse click listeners should not wait, sleep, join or the like, they need to return promptly. Until they do no graphics updates will have any effect. This is because the event listeners and the graphics updates all take place on the same thread (the dispatcher thread).

Start the thread and return. There's no point in having two threads if one it to complete before the other starts, might as well do both actions on one.

malcolmmca at 2007-7-28 17:20:23 > top of Java-index,Java Essentials,Java Programming...
# 2

thank you!

So what kind of structure of commands you suggest for dispatchers etc. How I can combine midi playing commands, mouse listener and graphics update commands etc. into a single thread?

Please, additional clarifications are highly appreciated

-wondeful-?

wonderful123a at 2007-7-28 17:20:23 > top of Java-index,Java Essentials,Java Programming...
# 3

Generally such a button callback first disables the button, then launches a background thread which does the sequence. When the thread finishes it re-enables the button again.

When these background threads need to update the GUI interface they should generally, use EventQueue.invokeLater(). This queues some code for execution back on the dispatcher thread.

malcolmmca at 2007-7-28 17:20:23 > top of Java-index,Java Essentials,Java Programming...