In the previous article we explained the problem of thread safety, so to solve the problem of thread safety , we have to use thread synchronization , to ensure that the threads do not affect each other and produce dirty data , let's talk about the specific implementation of it.
First, let's take a look at the example, we have a Outputter class for outputting
/*** * * Output class * @author Yangqingshan * */public class Outputter {public void output (String name) throws Interruptedexce ption {//output name one by one for (int i = 0; i < name.length (); i++) {System.out.print (Name.charat (i)); Thread.Sleep (10);}}
Then we also need a thread class for calling the thread
/*** * * Thread Synchronization Example * @author Yangqingshan * */public class Synchronizeddemo {public static void main (string[] args) {//Set Semantic one output class final outputter output = new Outputter ();//new thread, print name: Yangqingshannew thread () {public void run () {try {OUTPUT.O Utput ("Yangqingshan");} catch (Interruptedexception e) {e.printstacktrace ();}};}. Start ();//new thread, print name: Mayongchengnew thread () {public void run () {try {output.output ("Mayongcheng");} catch ( Interruptedexception e) {e.printstacktrace ();}};}. Start ();}}
Print out the results
Then we can add thread synchronization in the code block or method , first look at the code block .
/*** * * Output class * @author Yangqingshan * */public class Outputter {public void output (String name) throws Interruptedexce ption {synchronized (this) { //outputs the name individually for (int i = 0; i < name.length (); i++) {System.out.print (Name.charat (i)); Thread.Sleep (10);}}}
Method Plus thread synchronization
/*** * * Output class * @author Yangqingshan * */public class Outputter {public synchronized void output (String name) throws in terruptedexception {//output name one by one for (int i = 0; i < name.length (); i++) {System.out.print (Name.charat (i)); Thread.Sleep (10);}}
Thread-safe issues can be addressed initially through thread synchronization above
This site article is for baby bus SD. Team Original, reproduced must be clearly noted: (the author's official website: Baby bus )
Reprinted from "Baby bus Superdo Team" original link: http://www.cnblogs.com/superdo/p/4872142.html
[Javaweb Basics] 022. Thread Safety (ii)