public class SpinLock {
static ExecutorService executorService = Executors.newFixedThreadPool(5);
public static void main(String[] args) {
for (int i = 0;i<5;i++){
executorService.execute(new AaBbCc());
}
}
}
class AaBbCc implements Runnable{
static ReentrantLock lock = new ReentrantLock();
public void run(){
try {
boolean tryLock = lock.tryLock();
if(tryLock){
System.out.println(Thread.currentThread().getName()+":我已抢到锁了");
TimeUnit.SECONDS.sleep(1);
System.out.println(Thread.currentThread().getName()+":执行完毕");
}else {
System.out.println(Thread.currentThread().getName()+":我获取锁失败了");
TimeUnit.SECONDS.sleep(new Random().nextInt(5));
run();
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(lock.isLocked()){
System.out.println(Thread.currentThread().getName()+":我即将要释放锁");
lock.unlock();
}
}
}
}