Java multithreading security issues-synchronous modifiers to functions

Source: Internet
Author: User
Tags modifiers

Previous article solve security problems by selling tickets using synchronous code blocks
This article first explores how to identify such security issues and proposes a second approach (non-static function synchronized modification) to address security issues

/*Requirements: The bank has a public account vault has two depositors at the same time access to the account, 100 for a total of 3 times the purpose: whether the program has a security problem, if so, how to solve the idea: how to find the problem? 1, clear which code is multithreaded run code 2, explicitly shared data 3, clear multi-threaded running code which statements are operating the shared data*//*the Bank is a resource (private property and public method) in the program, and the custom run method in the Runnable interface subclass operates on the resource*/classbank{Private intsum; //Object obj = new Object ();     Public synchronized voidAddintN) {//synchronized (obj)//{sum = sum +N; Try{Thread.Sleep (10);}Catch(Exception e) {} System.out.println ("Sum=" +sum); //}    }}classCusImplementsrunnable{PrivateBank b=NewBank ();  Public voidrun () { for(intx=0; x<3; X + +) {B.add (100); }    }}classBanddemo { Public Static voidMain (string[] args) {Cus C=NewCus (); Thread T1=NewThread (c); Thread T2=NewThread (c);        T1.start ();        T2.start (); System.out.println ("Hello world!"); }}

Effect:

Hello world!
sum=100
sum=200
sum=300
sum=400
sum=500
sum=600

Java multithreading security issues-synchronous modifiers to functions

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.