Thread synchronization: When more than one thread accesses the same data resource, it causes incorrect data. Then, when simultaneous access must determine one thread access, other threads are temporarily inaccessible
Object interlock is proposed in Java to use synchronized to indicate that the thread is locked, can only be accessed by the current thread, and other threads are waiting, temporarily inaccessible
Instance:
Package com.exmaple.Thread;
public class Test5 extends thread{
private static Runnab R;
/**
* Thread synchronization causes incorrect data when multiple threads access the same data resource
* Then, when simultaneous access must determine a thread access, other threads are temporarily inaccessible
* Proposed object interlock in Java synchronized means that the thread is locked and can only
* Accessed by the current thread, other threads waiting, temporarily inaccessible
* @param args
*/
public static void Main (string[] args) {
TODO auto-generated Method Stub
R=new Runnab ();
Create two threads, set a thread name, and turn on
Test5 t=new Test5 ();
Thread t1=new thread (t);
Thread t2=new thread (t);
T1.setname ("name1");
T2.setname ("name2");
T1.start ();
T2.start ();
}
The main method implements the interface by invoking the method to get the name of the thread, so that different values can be obtained
@Override
public void Run () {
TODO auto-generated Method Stub
R.add (Thread.CurrentThread (). GetName ());
}
}
Class Runnab {
int num=0;
If there is no synchronized, thread T1 execution, num=1, thread t1 sleep; thread T2 execute, num=2, thread T2 hibernate; T1 perform print 2,t2 perform print 2
There is synchronized thread T1 execution, thread 2 waits, thread T1 executes num=1 thread t2 start execution num=2
Public synchronized void Add (String name) {
num++;
try{
Thread.Sleep (1);
}catch (Exception e) {
}
System.out.println ("+num+", "GE");
}
}
Thread Synchronization (1)