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