Thread Synchronization (1)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.