Synchronisation über einen globalen Monitor

This commit is contained in:
ngb
2022-07-08 07:44:49 +02:00
parent 9ee7c606fe
commit ced0aa6842
2 changed files with 37 additions and 7 deletions

View File

@@ -1276,10 +1276,37 @@ public class Zeichenmaschine extends Constants {
// Zeichenthread
////
/**
* Globaler Monitor, der einmal pro Frame vom Zeichenthread freigegeben
* wird. Andere Threads können {@link Object#wait()} auf dem Monitor
* aufrufen, um sich mit dem Zeichenthread zu synchronisieren. Der
* {@code wait()} Aufruf sollte sich zur Sicherheit in einer Schleife
* befinden, die prüft, ob sich der Aktuelle {@link #tick} erhöht hat.
* <pre><code>
* int lastTick = Constants.tick;
*
* // Do some work
*
* while( lastTick >= Constants.tick ) {
* synchronized( Zeichenmaschine.globalSyncLock ) {
* try {
* Zeichenmaschine.globalSyncLock.wait();
* } catch( InterruptedException ex ) {}
* }
* }
* // Next frame has started
* </code></pre>
* <p>
* Die {@link schule.ngb.zm.tasks.FrameSynchronizedTask} implementiert eine
* {@link schule.ngb.zm.tasks.Task}, die sich automatisch auf diese Wiese
* mit dem Zeichenthread synchronisiert.
*/
public static final Object globalSyncLock = new Object[0];
class Zeichenthread extends Thread {
public Zeichenthread() {
super(Zeichenthread.class.getSimpleName());
super(APP_NAME);
//super(APP_NAME + " " + APP_VERSION);
}
@@ -1328,6 +1355,9 @@ public class Zeichenmaschine extends Constants {
}
runTasks();
synchronized( globalSyncLock ) {
globalSyncLock.notifyAll();
}
// delta time in ns
long afterTime = System.nanoTime();
@@ -1414,6 +1444,7 @@ public class Zeichenmaschine extends Constants {
}
class InputListener implements MouseInputListener, MouseMotionListener, MouseWheelListener, KeyListener {
@Override
public void mouseClicked( MouseEvent e ) {
enqueueEvent(e);

View File

@@ -10,7 +10,7 @@ public abstract class FrameSynchronizedTask extends Task {
private static final Thread getMainThread() {
if( mainThread == null ) {
mainThread = Thread.currentThread();
if( !mainThread.getName().equals("Zeichenthread") ) {
if( !mainThread.getName().equals(Constants.APP_NAME) ) {
// Need to search for main Zeichenthread ...
}
}
@@ -21,7 +21,7 @@ public abstract class FrameSynchronizedTask extends Task {
public void run() {
running = true;
int lastTick = 0;
Thread lock = getMainThread();
Object lock = Zeichenmaschine.globalSyncLock;
while( running ) {
lastTick = Constants.tick;
@@ -29,12 +29,11 @@ public abstract class FrameSynchronizedTask extends Task {
synchronized( lock ) {
while( lastTick >= Constants.tick ) {
/*try {
try {
lock.wait();
} catch( InterruptedException e ) {
// We got interrupted ...
}*/
Thread.yield();
}
}
}
}