I have GraphicView which extends SurfaceView. I need it for drawing a graphics. I need also onTouchEvent. But problem is… I don’t know how to describe it 🙂 here’s my code:
public class GraphicView extends SurfaceView implements Runnable {
private boolean mutexOpened = true;
public boolean onTouchEvent( MotionEvent me ) {
if ( mutexOpened ) {
mutexOpened = false;
Log.d( "mutex", "ACTION 1" );
switch ( action ) {
case MotionEvent.ACTION_DOWN: {
int rnd = new Random().nextInt( 40000 ) + 1000;
for ( int i = 0; i < rnd; i++ ) {} // it's some long action :)
Log.d( "mutex", "ACTION 2: down" );
break;
}
}
Log.d( "mutex", "ACTION 2: end" );
mutexOpened = true;
}
}
public void run() {
while ( true ) {
if ( mutexOpened ) {
Log.d( "mutex", "!!! RUN !!!!" );
}
}
}
}
I use the mutex technique which (I suppose) has to control my threads. But in the Log I see following:
!!! RUN !!!!
ACTION 1
!!! RUN !!!!
ACTION 2: down
ACTION 2: end
But why?? Why the second “!!! RUN !!!!” runs between “ACTION 1” and “ACTION 2” when the mutex is closed? It’s impossible! :)))
I tried to do next:
public void run() {
while ( true ) {
if ( mutexOpened ) {
mutexOpened = false; // close mutex
Log.d( "mutex", "!!! RUN !!!!" );
mutexOpened = true; // open mutex
}
}
}
but… FAIL :)) onTouchEvent never runs at all :D))) Does anybody know how to solve this problem?
You have to synchronize the access to mutexOpened: run() may be reading mutexOpened immediately before you set it to false and may be printing RUN!!! immediately after you print “ACTION 1”.
Use the Java keyword synchronized to synchronize the access to mutexOpened. On run() you can use wait(), which releases the lock during the sleep phase.
And if you use the synchronized keyword, you don’t need the variable mutexOpened at all.
Also, try to don’t execute long operations in the GUI thread (that comment “it’s some long action”): that should be executed in a separate thread