Introduction to java multi-thread synchronization and multi-thread lock

Source: Internet
Author: User

Thread synchronization and lock problems. Let's look at an example first,

In the following example, we want two threads to reduce m variables.

The code is as follows: Copy code

Packagecom. javaer. thread;
PublicclassSysTestimplementsRunnable {
Intm = 10;

Publicstaticvoidmain (String [] args ){
SysTests1 = newdestest ();
Threadt1 = newThread (s1, "Thread-t1 ");
Threadt2 = newThread (s1, "Thread-t2 ");
T1.start ();
T2.start ();

}
Publicvoidreduce (){
M --;
}
@ Override
Publicvoidrun (){
While (m & gt; 0)
{
Try {
Thread. sleep (1 );
} Catch (InterruptedExceptione ){
// TODOAuto-generatedcatchblock
E. printStackTrace ();
}
This. reduce ();
System. out. println (Thread. currentThread (). getName () + "m value:" + m );

}

}

}

Thread-t1m value: 8
Thread-t2m value: 8
Thread-t1m value: 7
Thread-t2m Value: 6
Thread-t1m value: 5
Thread-t2m value: 4
Thread-t1m value: 3
Thread-t2m value: 2
Thread-t1m value: 0
Thread-t2m value: 0
The reduce operation is executed by two threads without any control, so there are two 8 cases.

If we want the thread to be executed in a certain order, we can synchronize it.

Use the synchronized keyword to synchronize the code for modifying variables.

Here we lock the reduce operation

Publicsynchronizedvoidreduce ()
To achieve what we want.

Principles of java synchronization locks

An object has only one lock. Therefore, if a thread acquires the lock, no other thread can obtain the lock until the first thread releases (or returns) the lock. This also means that no other thread can enter the synchronized method or code block on the object until the lock is released.

Key points of synchronization and lock
1. You can only synchronize methods, but not variables and classes.
2. Do not synchronize all methods. Just synchronize the necessary methods.
3. If a synchronized method is being called by one thread, other threads cannot be called and enter the waiting state as long as the method is released.
4. The lock is not automatically released when the thread is sleeping.
5. Synchronization will damage efficiency. The goal of multithreading is concurrency, and the goal of locking is anti-concurrency. So try to narrow the lock range.
6. Data that can be changed in non-static fields is usually accessed using non-static methods.
For data that can be changed in static fields, it is usually accessed using static methods.

When to use synchronization
1. Access the dependent resources, for example, when you need to collect tasks from a task pool.
2. When multiple threads modify the same public variable

Deadlock

When a thread occupies the lock, a problem occurs, such as a crash. All other waiting threads are congested, causing a deadlock. Once a deadlock occurs, the program will die.

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.