Lock與synchronized的異同

主要相同點:Lock能完成synchronized所實現的全部功能 java

主要不一樣點:Lock有比synchronized更精確的線程語義和更好的性能。synchronized會自動釋放鎖,而Lock必定要求程序員手工釋放,而且必須在finally從句中釋放。Lock還有更強大的功能,例如,它的tryLock方法能夠非阻塞方式去拿鎖。 程序員

舉例說明(對下面的題用lock進行了改寫): ide

package com.huawei.interview; 性能

 

import java.util.concurrent.locks.Lock; this

import java.util.concurrent.locks.ReentrantLock; spa

 

public class ThreadTest { 線程

 

     /** class

      * @param args import

      */ 程序

    

     private int j;

     private Lock lock = new ReentrantLock();

     public static void main(String[] args) {

          // TODO Auto-generated method stub

          ThreadTest tt = new ThreadTest();

          for(int i=0;i<2;i++)

          {

              new Thread(tt.new Adder()).start();

              new Thread(tt.new Subtractor()).start();

          }

     }

 

     private class Subtractor implements Runnable

     {

 

          @Override

          public void run() {

              // TODO Auto-generated method stub

              while(true)

              {

                   /*synchronized (ThreadTest.this) {             

                        System.out.println("j--=" + j--);

                        //這裏拋異常了,鎖能釋放嗎?

                   }*/

                   lock.lock();

                   try

                   {

                        System.out.println("j--=" + j--);

                   }finally

                   {

                        lock.unlock();

                   }

              }

          }

         

     }

    

     private class Adder implements Runnable

     {

 

          @Override

          public void run() {

              // TODO Auto-generated method stub

              while(true)

              {

                   /*synchronized (ThreadTest.this) {

                   System.out.println("j++=" + j++);

                   }*/

                   lock.lock();

                   try

                   {

                        System.out.println("j++=" + j++);

                   }finally

                   {

                        lock.unlock();

                   }                 

              }            

          }

         

     }

相關文章
相關標籤/搜索