Java multi-threading, synchronized access, thread lock, lock objects, ReentrantLock, synchronized

1. Why synchronize access to the data?

  When two or more threads need to share access to the same data, shared data corruption can occur.

2. To achieve a synchronized manner

  2.1 ReentrantLock类

    School class:

        class School{
        
            private int stuNum;
            private Lock lock;
private Condition condition;
        
            public School(int stuNum) {
                this.stuNum = stuNum;
                lock = new ReentrantLock();
                condition = lock.newCondition();
            }
        ......

    Wherein the object lock is locked, condition is a condition of the object,

    usage:

        public void stuNums1(){
            lock.lock();
            try{
                while (stuNum < 20){
                    System.out.println(stuNum+" < 20,等待数量变为20");
                    condition.await();
                }
                stuNum -= 5;
                System.out.println(Thread.currentThread().toString() + ":" + stuNum);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock () ; 
            } 

        } 
        public  void stuNums2 () {
             Lock.lock () ;
             the try { 
                stuNum + =. 1 ; 
                System.out.println (Thread.currentThread () toString (). + ":" + stuNum);
                 IF (stuNum> = 20 is ) { 
                    System.out.println (stuNum + "> 20 is the start of the wake-up threads waiting set" );
                     condition.signalAll () ; 
                } 
            } the finally {
                 lock.unlock () ; 
            }

        }

    When the condition object calls await () method when the current thread into the wait set, is blocked until another thread invokes signalAll on the same conditions () method.

 

Guess you like

Origin www.cnblogs.com/lovleo/p/11318623.html