可重入锁
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Phone implements Runnable{
public synchronized void sendSMS()throws Exception{
System.out.println(Thread.currentThread().getId() + "\t invoked sendSMS()");
sendEmil();
}
public synchronized void sendEmil() throws Exception{
System.out.println(Thread.currentThread().getId()+ "\t #########invoked sendEmil()");
}
Lock lock = new ReentrantLock();
@Override
public void run() {
get();
}
public void get(){
lock.lock();
lock.lock();
try {
System.out.println(Thread.currentThread().getName()+ "\t invoked get()");
set();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
lock.unlock();
}
}
public void set(){
lock.lock();
try {
System.out.println(Thread.currentThread().getName()+ "\t ###########invoked set()");
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
public class ReenterLockDemo1 {
public static void main(String[] args) {
Phone phone = new Phone();
new Thread(()->{
try {
phone.sendSMS();
} catch (Exception e) {
e.printStackTrace();
}
},"t1").start();
new Thread(()->{
try {
phone.sendSMS();
} catch (Exception e) {
e.printStackTrace();
}
},"t2").start();
Thread t3 = new Thread(phone,"t3");
Thread t4 = new Thread(phone,"t4");
t3.start();
t4.start();
}
}
运行结果