Article View: comp.lang.java.programmer
Article #642Re: The best synchronized Paint!
From: David Holmes
Date: Sat, 27 Mar 1999 00:00
Date: Sat, 27 Mar 1999 00:00
69 lines
2893 bytes
2893 bytes
David Holmes wrote in message <7d9jcc$ki5$1@sunb.ocs.mq.edu.au>...
> while (true){
>mainloop:
> lastPaint = System.currentTimeMillis();
> repaint();
> synchronized(this){
> int origSignals = signals;
The above is incorrect. My apologies. That's what happens when you write
these things on the fly.
In the above the the event thread could complete the execution of update()
in response to the repaint() before the above thread has starting waiting -
a classic lost wakeup problem (though the timeout would stop the thread from
hanging). A correct version is given below.
David
---------------------
public void run (){
long lastPaint = 0;
while (true){
mainloop:
synchronized(this){
lastPaint = System.currentTimeMillis();
repaint();
int origSignals = signals;
while(true){
try { wait(timeout); } catch(InterruptedException ie){}
// either signalled or timedout or spurious
if (origSignals != signals) break; // notified
else {
long now = System.currentTimeMillis();
if (now - lastPaint > timeout)
// we timed out which probably means the repaint
// was ignored, so restart the main loop
continue mainloop;
}
// else spurious so re-wait
}
}
}
// we were signalled so see if enough time has elapsed
// since the last repaint
long now = System.currentTimeMillis();
long sleepTime = (now - lastPaint) - appletSpeed;
if(sleepTime>0){
try {
Thread.sleep(sleepTime);
}
catch(InterruptedException e) { }
}
}
}
public void update(Graphics g){
paint(g);
synchronized(this){
signals++;
notifyAll(); // notify() will do if only ever one thread
}
}
public void paint(Graphics g){
// paint as appropriate
}
Technical Details
Message-ID:
<7dhqpu$m3h$1@sunb.ocs.mq.edu.au>Path:
arc1-ca.pugleaf.net!unknown!not-for-mailReferences:
<36F75CF1.37367641@greydirect.dk> <7d9jcc$ki5$1@sunb.ocs.mq.edu.au>Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: 100145,e7dc548027defe93 X-Google-Attributes: gid100145,public X-Google-Thread: f9a23,e7dc548027defe93 X-Google-Attributes: gidf9a23,public X-Google-Thread: f5e83,e7dc548027defe93 X-Google-Attributes: gidf5e83,public X-Google-Thread: 10a146,e7dc548027defe93 X-Google-Attributes: gid10a146,public From: "David Holmes" <dholmes@mri.mq.edu.au> Subject: Re: The best synchronized Paint! Date: 1999/03/27 Message-ID: <7dhqpu$m3h$1@sunb.ocs.mq.edu.au> X-Deja-AN: 459610151 References: <36F75CF1.37367641@greydirect.dk> <7d9jcc$ki5$1@sunb.ocs.mq.edu.au> X-MimeOLE: Produced By Microsoft MimeOLE V4.72.3110.3 Organization: Macquarie University, NSW, Australia Newsgroups: comp.lang.java.programmer,comp.lang.java.softwaretools,dk.edb.programmering.java,microsoft.public.java.visualj++