The difference between synchronized and lock
- Synchronized automatically locks, requiring manual locking
- Synchronized is a Java keyword and lock is an interface
- Synchronized cannot determine whether to obtain a lock. Lock can be determined by trylock
- Synchronized requires waiting, and lock can be set to respond to interrupt locks to stop waiting
- Synchronized non-fair lock, which can jump the queue. Lock automatically selects whether it is fair or unfair
- Synchronized works for a small number of synchronization problems and Lock works for a large number of synchronization problems
- 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
- Manually lock the device to unlock it
- 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