Java multi-Thread synchronization basics

Source: Internet
Author: User

On the road to Java learning there are always some troublesome things that take some time to understand, such as the multi-threading that a person thinks is bad.

Threads are run in parallel

Because it is a side-by-side operation, resource preemption sometimes occurs, which leads to parameter changes;

Like Jiangzi.

Package seer. threads; Public classSumarray {Private intsum; //in this place Sumarry () is not synced without sync ...     Public intSumarray (int[] sums) {Sum=0;//Reset Initialize sum         for(inti =0; i < sums.length; i++) {sum+=Sums[i]; Try{Thread.Sleep (Ten);            When a task switch occurs, it is intentional to allow the switchover to occur (it is absolutely not possible if the synchronized is added). } Catch(interruptedexception e) {System. out. println ("Thread Break");            E.printstacktrace (); }        }        returnsum; }}//=========================================================================================================== classMyThread implements Runnable {Thread thrd; StaticSumarray SA =NewSumarray (); int[] A; intanswer; //constructs a thread     PublicMyThread (String name,int[] nums) {THRD=NewThread ( This, name); A=Nums; }    //Create a factory method to create and start a thread     Public StaticMyThread Createandstart (String name,int[] nums) {MyThread MYTHRD=NewMyThread (name, nums);        MyThrd.thrd.start (); returnMYTHRD; } @Override Public voidrun () {intsum; System. out. println (Thrd.getname () +"Start"); //here, the call to Sumarray is synchronized on the SA object//synchronized (SA) {Answer =Sa.sumarray (a); System. out. println (Thrd.getname () +"The result of the calculation is:"+answer);//        }System. out. println (Thrd.getname () +"End"); }}//=========================================================================================================== //create a class that has a main functionclasssync{ Public Static voidMain (string[] args) {int[] arr = {2,3,2,3,2}; MyThread MYT= Mythread.createandstart ("Thread 1", arr); MyThread myt1= Mythread.createandstart ("Thread 2", arr); }}


Thread 2 starts
Thread 1 starts
The result of thread 1 calculation is: 22
The result of thread 2 calculation is: 22
Thread 1 Ends
Thread 2 Ends

PS The result is 22 because there is a sleep so that you can more objectively find the difference between two threads

Two threads are created, and two threads execute a method in a sequential manner, and because of the parallel nature of the thread, two threads can enter a method at the same time, which can result in a change in the number of data operations, which directly affects the result.

There are two ways of doing this:

 Method 1:

Adding the Synchronized keyword to the Sumarray () method plus the Sumarray () name after the keyword is called a "synchronous method"

  PublicSynchronizedintSumarray (int[] sums) {Sum=0;//Reset /Initialize sum         for(inti =0; i < sums.length; i++) {sum+=Sums[i]; Try{Thread.Sleep ( -); } Catch(interruptedexception e) {System. out. println ("Thread Break");            E.printstacktrace (); }        }        returnsum; }

Plus synchronized, no matter what kind of threading situation, you can guarantee that each time only one thread into this method, the other threads wait until the current thread is finished to enter.

    Method 2

Using synchronous statements

   
static Sumarray sa = new sumarray ();

Public voidrun () {intsum; System. out. println (Thrd.getname () +"Start"); synchronized (SA) {//This section answer=Sa.sumarray (a); System. out. println (Thrd.getname () +"The result of the calculation is:"+answer); } System. out. println (Thrd.getname () +"End"); }

The basic format of the synchronization statement:

Synchronized (ref) {

Method body

}

Ref here is a reference to the Synchronized object, and a normal object referenced directly in the code above

Both methods can be implemented to synchronize the method to prevent the situation of data disturbance caused by multi-threaded environment

So what is the difference between synchronous and synchronous statements?

Although a simple and efficient way to synchronize a method, this method does not apply to all situations,

For example, some methods that are not modified by synchronized may need to be synchronized. This occurs when you want to use a class that has a third-party creation and cannot access the source code.

This time use synchronous code block

Each need, two usages, the same effect.

  

Java multi-Thread synchronization basics

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.