Reentrantlock用于替代synchronized
package cn.qqjx.thread;
import java.util.concurrent.TimeUnit;
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 ...