Thread-safe and non-thread-safe are the classic problems of multithreading, and non-line Shuo assemblies occur when multiple threads concurrently access the same object.
Note 1:
Non-thread-safe issues exist in instance variables, and there is no non-threading security issue if the private variable is inside the method.
Instance variables are common to all methods of an object, and static variables are common to all objects of the class, and in multithreaded situations, you need to consider thread safety issues.
NOTE 2:
If it is concurrent access, read-only and no-write, then there will be no non-thread security issues, if you are involved in concurrent read and write, you need to consider thread safety issues.
Public classVar {PrivateInteger Count; PublicInteger updatecount (integer count)throwsinterruptedexception { This. count=count; Thread.Sleep (1000); return This. Count; }} Public classThreadaextendsthread{Privatevar var; PublicThreada (var var) { This. var =var; } @Override Public voidrun () {Try{Integer Newcount= Var.updatecount (200); System.out.println ("Set=200;return=" +newcount); } Catch(interruptedexception e) {e.printstacktrace (); } }} Public classThreadbextendsThread {Privatevar var; Publicthreadb (var var) { This. var =var; } @Override Public voidrun () {Try{Integer Newcount= Var.updatecount (100); System.out.println ("Set=100;return=" +newcount); } Catch(interruptedexception e) {e.printstacktrace (); } }}/*** Created by Wangbin10 on 2018/7/11. * Output: *set=100;return=100 *set=200;return=100*/ Public classRun { Public Static voidMain (string[] args) {var var=NewVar (); Threada a=NewThreada (VAR); THREADB b=NewThreadb (VAR); A.start (); B.start (); }}
The solution is simple, give updatecount locking:
Public class Var { private Integer count; synchronized Public throws interruptedexception { this.count=count; Thread.Sleep (+); return This . Count; }}
This time the output is normal.
Java Multi-thread thread safety