The difference between synchronized and lock

  1. Synchronized automatically locks, requiring manual locking
  2. Synchronized is a Java keyword and lock is an interface
  3. Synchronized cannot determine whether to obtain a lock. Lock can be determined by trylock
  4. Synchronized requires waiting, and lock can be set to respond to interrupt locks to stop waiting
  5. Synchronized non-fair lock, which can jump the queue. Lock automatically selects whether it is fair or unfair
  6. Synchronized works for a small number of synchronization problems and Lock works for a large number of synchronization problems
  7. Synchronized pessimistic lock optimistic lock
  • Synchronized reentrant, non-judgmental, non-fair, and non-interruptible;
  • Lock can be reentrant, can determine, interrupt and fair or not can be set

Lock to achieve production and consumption problems

  1. Manually lock the device to unlock it
  2. Replace object monitor methods (wait, notify, and notifyAll) with condition
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Test2 {
    public static void main(String[] args) {
        Data2 date = new Data2();
        // Omit multithreaded start here, code same as above
}
class Data2{
    private int number=0;
    private Lock lock=new ReentrantLock();
    private  Condition condition = lock.newCondition();
    public  void increment(a) throws InterruptedException {
        lock.lock();
        try{
            while(number! =0)
                condition.await();/ / instead of wait
            number++;
            System.out.println(Thread.currentThread().getName()+" incr->"+number);
            condition.signal();/ / instead of notify
        }catch (Exception exception){
            System.err.println("incr wrong");;
        }finally{ lock.unlock(); }}public void decrement(a)throws InterruptedException{
        lock.lock();
        try {
            while ( number==0)
                condition.await();
            number--;
            System.out.println(Thread.currentThread().getName()+" decr->"+number);
            condition.signal();
        }catch (Exception ex){
            System.err.println("decr wrong");
        }finally{ lock.unlock(); }}}Copy the code