Java thread 05

Source: Internet
Author: User

Replaced Synchronization

A declared synchronous method of the parent class under the Inheritance architecture can be overwritten by more specific child classes and declared as non-synchronous.

Example

/*** The Synchronized Method of the parent class can be changed to a non-Synchronized Method in the subclass * @ author wangyancheng * @ version 2012-11-12 */public class synextends {public static void main (string [] ARGs) {parentclass pcinst = new subclass (); // new parentclass (); set <integer> resultsets = collections. synchronizedset (New treeset <integer> (); createthread (pcinst, resultsets); CR Eatethread (pcinst, resultsets);} public static void createthread (final parentclass pcinst, final set <integer> valueset) {New thread (New runnable () {public void run () {While (true) {INTEGER tmpi = pcinst. dowork (); If (! Valueset. add (tmpi) {Throw new illegalstateexception ("incorrect data status, repeated :". concat (tmpi. tostring ();} Try {thread. sleep (100);} catch (interruptedexception IE) {IE. printstacktrace ();}}}}). start () ;}} class parentclass {private volatile int index; Public synchronized integer dowork () {Return Index ++ ;}} class subclass extends parentclass {private int index; @ override public integer dowork () {Return Index ++ ;}}

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.