Reentrantlock用于替代synchronized(一)

								Reentrantlock用于替代synchronized
package cn.qqjx.thread;

import java.util.concurrent.TimeUnit;

/*
 * Reentrantlock用于替代synchronized
 * 本例中由于m1锁定this,只有m1执行完毕的时候,m2才能执行
 * 这里是复习synchronized最原始的语义
 *  @Auther  wangpeng
 * @Date 2021/1/9
 */

public class T01_ReentrantLock1 {
    
    

    synchronized void m1() {
    
    
        for (int i = 0; i < 10; i++) {
    
    
            try {
    
    
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "---------" + i);
            if (i == 2) m2();
        }

    }

    synchronized void m2() {
    
    
        System.out.println(Thread.currentThread().getName()+ "---------"+"m2 ...");
    }

    public static void main(String[] args) {
    
    
        T01_ReentrantLock1 rl = new T01_ReentrantLock1();
        new Thread(() -> rl.m1(), "thread-1").start();
        try {
    
    
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
        new Thread(() -> rl.m2(), "thread-2").start();
    }

}
thread-1---------0
thread-1---------1
thread-1---------2
thread-1---------m2 ...
thread-1---------3
thread-1---------4
thread-1---------5
thread-1---------6
thread-1---------7
thread-1---------8
thread-1---------9
thread-2---------m2 ...

猜你喜欢

转载自blog.csdn.net/m0_52936310/article/details/112407480