package com.thread.utils;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.IntStream;
public class ReentrantLockTest {
final static Lock lock = new ReentrantLock();
public static void main(String[] args) {
IntStream.range(0,2).forEach(i->new Thread(){
@Override
public void run() {
needlockBySync();
}
});
new Thread(){
@Override
public void run() {
testUnInterrputibly();
}
}.start();
}
private static void needlockBySync() {
synchronized (ReentrantLockTest.class){
try {
lock.lock();
}finally {
lock.unlock();
}
}
}
public static void testTrylocky(){
if (lock.tryLock()){
try {
System.out.println(Thread.currentThread().getName()+" get lock and will do");
while (true){}
}finally {
lock.unlock();
}
}else {
System.out.println(Thread.currentThread().getName()+" not get lock");
}
}
public static void testUnInterrputibly(){
try {
lock.lockInterruptibly();
System.out.println(Thread.currentThread().getName()+" get lock and will do");
while (true){}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void needLock(){
try {
lock.lock();
System.out.println(Thread.currentThread().getName()+" get lock and will do");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}finally {
lock.unlock();
}
}
}