Synchronized and compare the ReentranLock

Concurrent programming problem is most vulnerable to security issues, so there are two solutions

  • Using the synchronization method or synchronized block (Synchronized keyword)

  • Use locking mechanism (ReentranLock)             

Synchronization method and a synchronization block (Synchronized keyword) is implemented on the JVM, relatively coarse-grained advantage is simple and crude error prone, but the performance is not very good.

Lock mechanism is a lock display, enables a more fine-grained control. Risk is the need to control their own release the lock, otherwise easily lead to deadlock.

ReentrantLock

ReentrantLock: reentrant lock, only ReentrantLock Lock class implements the interface, and provides more ReentrantLock method. The following examples look through some specific look at how to use ReentrantLock. We can take a look Lock interfaces, their previous attempts to write a custom lock out is to realize the Lock interface, and then combined with AQS (AbstractQueuedSynchronizer, scheduler) to achieve.

Look at the code

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadSafe {
    private static Lock lock = new ReentrantLock();
    private volatile static Integer i = 10;
    public static void main(String[] args) {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                try {
                    System.out.println("thread1获得锁");
                    System.out.println("T1 i的值:" + i);
                    i++;
                    System.out.println("T1 i的值:" + i);
                }finally {
                    System.out.println("thread1释放锁");
                    lock.unlock();
                }
            }
        });
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                try {
                    System.out.println("thread获得锁");
                    i = 12;
                    System.out.println("i的值:" + i);
                }finally {
                    System.out.println("thread释放锁");
                    lock.unlock();
                }
            }
        });
        thread.start();
        thread1.start();
//        for (int x = 0; x < 15; x++) {
//            System.out.println(thread.getState() + "XXXX");
//            System.out.println(thread1.getState() + "X");
//        }
    }
}

 This also solve thread safety issues.

Lock there is a method in the interface:

public interface Lock {
    void lock();
    void lockInterruptibly() throws InterruptedException;
    boolean tryLock();
    boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
    void unlock();
    Condition newCondition();
}

Wherein the lock () method is used to obtain the lock. If the lock has been acquired by another thread is waiting.
unlock () to release the lock, if the object is not locked, an exception is thrown.

tryLock () method returns a value that represents the attempt to acquire the lock, if the acquisition succeeds, it returns true, if the acquisition fails (ie, the lock has been acquired by another thread), false returns, also said that this method anyway It will return immediately. I will not have to wait in that when not get the lock.

tryLock (long time, TimeUnit unit) method and tryLock () method is similar, but the difference is that this method when the lock will not get to wait for some time, if it can not get the lock, it returns within the time periods false. If you get if you start to get a lock or lock in period of waiting, it returns true.

lockInterruptibly () method is rather special, when to acquire lock This way, if the thread is waiting to acquire a lock, then the thread is able to respond to the interrupt, the interrupt latency that is state of the thread. Thus leaving said that when two threads simultaneously by lock.lockInterruptibly () want to get a lock, if at this time to acquire lock A thread, and the thread B is only waiting, the call threadB.interrupt () method of the thread B able to interrupt the process of waiting for thread B

Condition we can see it as a multi-threaded tools to coordinate communication, newCondition () Returns a new Condition instance that is bound to this Lock instance.

Guess you like

Origin www.cnblogs.com/cq-yangzhou/p/11326829.html