Duplicar posible:
Java Synchronization¿Qué hace synchronized()/wait()/notifyAll() en Java?
estoy leyendo el libro partir Juegos Android.
Utiliza synchronized()
mucho pero realmente no entiendo lo que hace. No he usado Java en mucho tiempo y no estoy seguro si alguna vez utilicé el multihilo.
En los ejemplos de Canvas usa synchronized(this)
. Sin embargo, en el ejemplo de OpenGL ES, crea un objeto llamado stateChanged
y luego usa synchronized(stateChanged)
. Cuando el estado del juego cambia que llama stateChanged.wait()
y luego stateChanged.notifyAll();
Algunos código:
Object stateChanged = new Object();
//The onPause() looks like this:
public void onPause()
{
synchronized(stateChanged)
{
if(isFinishing())
state = GLGameState.Finished;
else
state = GLGameState.Paused;
while(true)
{
try
{
stateChanged.wait();
break;
} catch(InterruptedException e)
{
}
}
}
}
//The onDrawSurface looks like this:
public void onDrawFrame(GL10 gl)
{
GLGameState state = null;
synchronized(stateChanged)
{
state = this.state;
}
if(state == GLGameState.Running)
{
}
if(state == GLGameState.Paused)
{
synchronized(stateChanged)
{
this.state = GLGameState.Idle;
stateChanged.notifyAll();
}
}
if(state == GLGameState.Finished)
{
synchronized(stateChanged)
{
this.state = GLGameState.Idle;
stateChanged.notifyAll();
}
}
}
//the onResume() looks like this:
synchronized(stateChanged)
{
state = GLGameState.Running;
startTime = System.nanoTime();
}
(En serio) ¿buscó algo en cualquier lugar antes de preguntar esto? Incluso buscar Stack Overflow? –
Sí, lo hice ... @Joachim Sauver esa pregunta no cubre wait()/notify() –
Acaba de agregar wait()/notify() - debe intentar formar la pregunta correctamente la primera vez en lugar de construyéndolo en vivo. –