Refer to Java multithreading Design Mode
When the alert conditions are not met, they are immediately interrupted.
// If any data is modified, it will be stored in block security public synchronized void save () throws ioexception {If (! Changed) {system. Out. println (thread. currentthread (). getname () + "balks"); return ;}Dosave (); changed = false ;}
// If there is any data modification, store it in block security to delete the synchronized method, and extend the time to increase the chance of an error. Public void save () throws ioexception {If (! Changed) {system. out. println (thread. currentthread (). getname () + "balks"); return;} dosave (); try {thread. sleep (100);} catch (interruptedexception e) {}changed = false ;}
Result: Repeated writes exist.
SaverThread calls doSave, content = No.0ChangerThread balksSaverThread calls doSave, content = No.1ChangerThread balksChangerThread calls doSave, content = No.2SaverThread calls doSave, content = No.2ChangerThread balksChangerThread calls doSave, content = No.4SaverThread calls doSave, content = No.4ChangerThread balksChangerThread calls doSave, content = No.6SaverThread calls doSave, content = No.7ChangerThread balksChangerThread calls doSave, content = No.8SaverThread calls doSave, content = No.9ChangerThread balksChangerThread calls doSave, content = No.10
Set timeout. If the timeout time expires and the alert condition is not met, an exception is thrown:
private static final long TIMEOUT = 30000;
Public synchronized request getrequest () {long start = system. currenttimemillis (); // start time while (queue. Size () <= 0 ){Long Now = system. currenttimemillis (); // current time long rest = timeout-(now-Start); // remaining time if (rest <= 0) {Throw new livenessexception ("thrown by" + thread. currentthread (). getname ());}Try {Wait (rest);} catch (interruptedexception e) {}} return (request) queue. removefirst ();}