Locking methods and static variables in threads

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.