线程中synchronized关键字和lock接口的异同

一、synchronized关键字

  1.可以用来修饰代码块 

        synchronized (this) {
            // 同步的关键字 this 表示当前线程对象
                if (num == 0) {
                    break;
                }
                num--;
                System.out.println(Thread.currentThread().getName()+"买了第"+(50-num)+"张票,剩余"+num+"张");
            }

2.可以用在方法上 修饰同步方法

    
//同步的方法在上边我们写好的 循环中调用

while (true) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(sellTicket()) {
break;
}

}




private synchronized boolean sellTicket() { if(num>0) { // 同步的关键字 this 表示当前线程对象 num--; System.out.println(Thread.currentThread().getName() + "买了第" + (10 - num) + "张票,剩余" + num + "张"); return false; }else { return true; } }

二、lock接口 

  1.用此接口要用     ReentrantLock l = new ReentrantLock();      ReentrantLock 实现类   l 表示实现类对象

    通过其实现类对象来调用Lock()这个方法来开启同步锁

    然后通过该对象在同步代码 结束的后边来释放同步锁

    

            try {
                l.lock();
                // 同步的关键字 this 表示当前线程对象
                if (num == 0) {
                    break;
                }
                num--;
                System.out.println(Thread.currentThread().getName() + "买了第" + (50 - num) + "张票,剩余" + num + "张");
            } catch (Exception e) {
                // TODO: handle exception
            } finally {
                l.unlock();
            }

不过最好把释放同步锁的动作放在 finally中 

这样无论同步代码中是否出现异常 都会释放这个同步锁 ,而不会导致死锁的问题。

小结;synchronized 和lock接口的区别

  

暂时大概就是这些了,后续想到的话再补充

猜你喜欢

转载自www.cnblogs.com/yifachen/p/11929652.html