public class LockTest implements Runnable {
public Lock lock = new ReentrantLock();
@Override
public void run(){
try {
method1();
} catch (Exception e) {
e.printStackTrace();
}
}
private void method1() throws Exception {
if (lock.tryLock(new Random().nextInt(5), TimeUnit.SECONDS)) {
System.out.println(Thread.currentThread().getName()+"获取到锁");
try {
lock.lock();
System.out.println("enter "+Thread.currentThread().getName());
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
} else {
System.out.println(Thread.currentThread().getName()+"获取不到到锁");
}
}
public static void main(String[] args) {
LockTest lockTest = new LockTest();
for (int i = 0; i < 5; i++) {
new Thread(lockTest, "name"+i).start();
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)