java lock锁

java lock锁,第1张

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();
        }
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/741973.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-28
下一篇 2022-04-28

发表评论

登录后才能评论

评论列表(0条)

保存