thread safety issues can be explained by bank transfer
1 /**2 * Traditional thread Mutex technology3 * @authorlitaiqing4 */5 Public classtraditionalthreadsynchronized {6 7 Public Static voidMain (string[] args) {8 Newtraditionalthreadsynchronized (). Init ();9 }Ten One Private voidinit () { A /** - * Internal classes access local variables, local variables must be final - * If this code is in main error, because static code block can not access the inner class the */ - FinalOutputer Outputer =NewOutputer (); - NewThread (NewRunnable () { - @Override + Public voidrun () { - while(true){ + Try { AThread.Sleep (1000); at}Catch(interruptedexception e) { - e.printstacktrace (); - } -Outputer.output ("Zhangxiaoxiang"); - } - } in }). Start (); - NewThread (NewRunnable () { to @Override + Public voidrun () { - while(true){ the Try { *Thread.Sleep (1000); $}Catch(interruptedexception e) {Panax Notoginseng e.printstacktrace (); - } theOutputer.output ("Lihuoming"); + } A } the }). Start (); + } - $ Static classoutputer{ $ Public voidoutput (String name) { - intLen =name.length (); - /* the * Locks are done with either object, but only the same object is mutually exclusive - * 1. Each class has only one copy of the bytecode file, which can be used for mutual exclusion lockWuyi * 2. Use this also line the * This can also be synchroized on the method shelves, - * But from the perspective of multithreading efficiency, reasonable refinement of the synchronization block granularity can improve the execution efficiency, Wu * So it's better to add synchroized in the internal code - */ About synchronized(Outputer.class){ $ for(inti = 0; i < Len; i++){ - System.out.print (Name.charat (i)); - } - System.out.println (); A } + } the /** - * The Output2 method is not synchronized because the method is added synchronized equals the This lock $ * But the static method, so this will fail, there will be problems. the * @paramname the */ the Public Static synchronized voidoutput2 (String name) { the intLen =name.length (); - synchronized(Outputer.class){ in for(inti = 0; i < Len; i++){ the System.out.print (Name.charat (i)); the } About System.out.println (); the } the } the } +}
3. Traditional thread Mutex technology