1 Use of-----Lock method:
Final ServletContext CTX = Request.getservletcontext (); This local variable is defined as a constant;
New Thread () {//written in inner class
public void Run () {
Addcount.add (CTX);
};
}.start ();
Class addcount{
Use class templates as locks
Public synchronized static void Add (ServletContext ctx) {-------Synchronized here is the Lock method----Lock is the class of the method
Integer count = (integer) ctx.getattribute ("Count");
count++;
Ctx.setattribute ("Count", count);
}
}
2-----with static variables as lock
ServletContext Ctx=request.getservletcontext (); there's no need to define constants here.
New MyThread (CTX). Start ();
--Write to external
Class MyThread extends thread{
private static String C = "ASD";//define a static variable here, so that the same lock is shared
Private ServletContext ctx=null;
Public MyThread (ServletContext ctx) {
This.ctx=ctx;
}
@Override
public void Run () {
SYSTEM.OUT.PRINTLN ("Threads running and running ...");
Synchronized (C) {This is the use of static variables to lock
Integer count = (integer) ctx.getattribute ("Count");
count++;
Ctx.setattribute ("Count", count);
}
}
}
Locking methods and static variables in threads