Why is the concept of thread synchronization? Why sync? What is thread synchronization? First look at a piece of code:
Package com.maso.test;
public class ThreadTest2 implements runnable{private testobj testobj = new Testobj ();
public static void Main (string[] args) {ThreadTest2 tt = new ThreadTest2 ();
thread T1 = new Thread (TT, "thread_1");
Thread t2 = new Thread (TT, "thread_2");
T1.start ();
T2.start (); @Override public void Run () {for (int j = 0; J < J + +) {in
t i = fix (1);
try {thread.sleep (1);
catch (Interruptedexception e) {e.printstacktrace ();
} System.out.println (Thread.CurrentThread (). GetName () + ": i =" + i);
' public int ' fix (int y) {return testobj.fix (y);
public class testobj{int x = 10; public int fix (intY) {return x = x-y; }
}
}
When you output the result, you will find that the variable x is operated concurrently by two threads, which can easily lead to misoperation. How can we solve this problem? With thread synchronization technology, plus synchronized keyword
public synchronized int fix (int y) {
return Testobj.fix (y);
}
Coupled with synchronization, you can see an orderly output from 9 to-10.
If the fix method added to the Testobj class can achieve synchronization?
public class testobj{
int x = 10;
public synchronized int fix (int y) {
return x = x-y;
}
}
If you add synchronized to a method, it is equivalent to
Synchronized (this) {
}