Brush 16 interview questions: the difference between synchronized and ReentrantLock of?

image.png




java concurrent programming is the programmer basic skills.

I was Li Fuchun, I prepare for the interview, the topics are:

the difference between synchronized and ReentrantLock of?

Both goods are java synchronization mechanisms, providing mutual exclusion semantics and visibility, when a thread access to resources, other threads must wait for the competition for resources or clogging.

Differences are as follows:

file



Thread Safety



It said security thread is a multithreaded scenario, shared correctness can modify the shape of the data.

From the semantic point of view, methods are thread-safe 2:
1, encapsulated, the data is not shared, privatized.
2, the data can not be modified, natural thread-safe does not exist. final, immutable;

thread-safe three characteristics:
Isolation: other related operations not interfering threads
sequential: serial semantics within the thread, to avoid rearrangement instruction;
visibility: local variable thread back to main memory should be modified on the use of the volatile keyword.


First look at an example of unsafe thread:
package org.example.mianshi.concurrent;

/**
 * 线程不安全例子,共享数据sharedState
 * @author lifuchun
 */
public class ThreadSafeSample {
    public int sharedState;

    public void nonSafeAction() {
        while (sharedState < 100000) {
            int former = sharedState++;
            int latter = sharedState;
            if (former != latter - 1) {
                System.out.printf("Observed data race, former is " +
                        former + ", " + "latter is " + latter);
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        final ThreadSafeSample sample = new ThreadSafeSample();
        Thread threadA = new Thread() {
            @Override
            public void run() {
                sample.nonSafeAction();
            }
        };
        Thread threadB = new Thread() {
            @Override
            public void run() {
                sample.nonSafeAction();
            }
        };
        threadA.start();
        threadB.start();
        threadA.join();
        threadB.join();
    }
}


Shared data, then only two threads changes, show inconsistency of data.


You can then transform the look, were used sychronized, ReetrantLock transformation, to ensure thread safety.

summary


Benpian compared the difference sychronized and ReetrantLock of;

then said thread-safe concept and means to ensure the thread.


image.png

The original is not easy, please indicate the source, let us complementarity and common progress, welcomed the multi-communication

Published 110 original articles · won praise 10 · views 20000 +

Guess you like

Origin blog.csdn.net/tian583391571/article/details/105148292