最常见的程序员面试题(5)Java/C++线程同步

来源:互联网 发布:炉石传说盒子数据在哪 编辑:程序博客网 时间:2024/06/05 21:08
Java线程同步是服务器技术的基础问题。大型网络服务器/应用服务器/数据库等均包含复杂的多线程实现。

(1) 最常见的多线程同步的问题是和Singleton设计模式相关的。为了保证多线程在访问Singleton实例的时候没有多线程冲突,需要对代码进行保护。

[java] view plaincopyprint?
  1. public class my {  
  2.     public static void main(String[] args) {  
  3.         my.Singleton.GetInstance();  
  4.     }  
  5.     static class Singleton{  
  6.         private static volatile Singleton inst=null;  
  7.         public static Singleton GetInstance(){  
  8.             if(inst==null){  
  9.                 synchronized(Singleton.class){//JVM memory barrier  
  10.                     inst=new Singleton();  
  11.                 }  
  12.             }  
  13.             return inst;  
  14.         }  
  15.         Singleton(){System.out.println("ctor");}  
  16.     }  
  17. }  
(2) Singleton的例子很简单,因为多线程保护集中在同一个函数当中。如果这种保护要跨越多个函数调用,那么"关键段"或者"synchronized"代码就失效了,如下所示。例如,对于银行ATM而言,"存款"和"取款"者两个函数调用是不能同时进行的,必须存在一个能管理全局的资源锁。
[java] view plaincopyprint?
  1. public class ATM{  
  2.     int m_nAmount;  
  3.     ATM(int m){  
  4.         m_nAmount=m;  
  5.     }  
  6.     class ClientThread1 extends Thread{  
  7.         public void run(){  
  8.             try{  
  9.                 while(true){  
  10.                     Deposit(10);  
  11.                     Thread.sleep(1000);  
  12.                     System.out.println(",thread1:"+m_nAmount);  
  13.                 }  
  14.             }catch(InterruptedException e){  
  15.                   
  16.             }  
  17.         }  
  18.         synchronized void Deposit(int amount){  
  19.             m_nAmount+=amount;  
  20.         }  
  21.     }  
  22.     class ClientThread2 extends Thread{  
  23.         public void run(){  
  24.             try{  
  25.                 while(true){  
  26.                     WithDraw(10);  
  27.                     Thread.sleep(1000);  
  28.                     System.out.println(",thread2:"+m_nAmount);  
  29.                 }  
  30.             }catch(InterruptedException e){  
  31.                   
  32.             }  
  33.         }  
  34.         synchronized void WithDraw(int amount){  
  35.             m_nAmount-=amount;  
  36.         }  
  37.     }  
  38.     public static void main(String[] args) {  
  39.         ATM re=new ATM(100);  
  40.         ATM.ClientThread1 th1= re.new ClientThread1();  
  41.         ATM.ClientThread2 th2= re.new ClientThread2();  
  42.         ATM.ClientThread1 th3= re.new ClientThread1();  
  43.         ATM.ClientThread2 th4= re.new ClientThread2();  
  44.         th1.start();  
  45.         th2.start();  
  46.         th3.start();  
  47.         th4.start();  
  48.     }  
  49. }  

    这段代码的执行结果会像是下面这样:
,thread2:100
,thread2:100
,thread1:90
,thread1:100
,thread2:100
,thread2:90
,thread1:80
,thread1:90
,thread2:100
,thread2:90
,thread1:80
,thread1:90
    原因前面已经说过了,因为无法保证两个函数能被互斥的访问。有一句名言,计算机领域的问题都可以通过引入一个中间层次得以解决,也就是说,为了解决这个问题,java1.5以后引入了新的包concurrent,这个包的内部去声明synchronized就行了。因此上面的代码会变成这样。这保证了没有Deposite或者WithDraw被同时执行造成潜在的数据冲突。多个线程每次只能执行一个Deposite或者WithDraw操作。
[java] view plaincopyprint?
  1. import java.util.concurrent.locks.*;  
  2. public class ATM {  
  3.     int m_nAmount=0;  
  4.     Lock m_lock=new ReentrantLock();  
  5.     ATM(int m){  
  6.         m_nAmount=m;  
  7.     }  
  8.     class ClientThread1 extends Thread{  
  9.         public void run(){  
  10.             try{  
  11.                 while(true){  
  12.                     m_lock.lock();  
  13.                     Save(10);  
  14.                     System.out.println(",thread1:"+m_nAmount);  
  15.                     m_lock.unlock();  
  16.                     Thread.sleep(1000);  
  17.                 }  
  18.             }catch(InterruptedException e){}  
  19.         }  
  20.         synchronized void Save(int amount){  
  21.             m_nAmount+=amount;  
  22.         }  
  23.     }  
  24.     class ClientThread2 extends Thread{  
  25.         public void run(){  
  26.             try{  
  27.                 while(true){  
  28.                     m_lock.lock();  
  29.                     WithDraw(10);  
  30.                     System.out.println(",thread2:"+m_nAmount);  
  31.                     m_lock.unlock();  
  32.                     Thread.sleep(1000);  
  33.                 }  
  34.             }catch(InterruptedException e){}  
  35.         }  
  36.         synchronized void WithDraw(int amount){  
  37.             m_nAmount-=amount;  
  38.             if(m_nAmount<0){  
  39.                 System.out.println("failed withdraw");  
  40.             }  
  41.         }  
  42.     }  
  43.     public static void main(String[] args) {  
  44.         ATM re=new ATM(15);  
  45.         ATM.ClientThread1 th1= re.new ClientThread1();  
  46.         ATM.ClientThread2 th2= re.new ClientThread2();  
  47.         ATM.ClientThread1 th3= re.new ClientThread1();  
  48.         ATM.ClientThread2 th4= re.new ClientThread2();  
  49.         th1.start();  
  50.         th2.start();  
  51.         th3.start();  
  52.         th4.start();  
  53.     }  
  54. }  


(3) 线程同步的问题,常见的是和synchronized关键字有关的。经典的问题之一是ATM取款机问题。因为windows的线程切换时间在10ms左右,因此下面这个程序就演示了100个线程同时存钱/取钱,最终的结果是不确定的。

[java] view plaincopyprint?
  1. public class my{   
  2.      public static void main(String[] args){   
  3.          ATM[] pArr=new ATM[100];   
  4.          for(int i=0;i<pArr.length;++i){   
  5.              pArr[i]=new ATM();   
  6.              pArr[i].start();   
  7.          }  
  8.          try{  
  9.              Thread.sleep(300);  
  10.          }catch(InterruptedException e){  
  11.              e.printStackTrace();  
  12.          }  
  13.          System.out.println("Final amount="+ATM.m_acc.m_amount);   
  14.      }   
  15.      static class Account{   
  16.          int m_amount;   
  17.          String m_name;   
  18.          Account(int m,String name){   
  19.              m_amount=m;   
  20.              m_name  =name;   
  21.          }   
  22.          void Deposit(int m){   
  23.              try{   
  24.                  int a=m_amount;   
  25.                  a+=m;   
  26.                  Thread.sleep(10);   
  27.                  m_amount=a;   
  28.              }catch(InterruptedException e){   
  29.                  e.printStackTrace();   
  30.              }   
  31.          }   
  32.          void WithDraw(int m){   
  33.              try{   
  34.                  int a=m_amount;   
  35.                  a-=m;   
  36.                  Thread.sleep(10);   
  37.                  m_amount=a;   
  38.              }catch(InterruptedException e){   
  39.                  e.printStackTrace();   
  40.              }   
  41.          }   
  42.      }   
  43.      static class ATM extends Thread{   
  44.          static Account m_acc=new my.Account(10,"self");   
  45.          public void run(){   
  46.              m_acc.Deposit(1);   
  47.              m_acc.WithDraw(1);   
  48.          }   
  49.      }   
  50. }   

        要克服这个问题,就要为Deposit和WithDraw函数加上synchronized锁,但是这还不够,因为这只能放置多个同时存,或者多个同时取,不能方式同时存取造成的冲突。因此同步的对象应该是this指针。注意主函数里面要让所有的子线程调用join函数,这样主线程等待所有子线程完成才打印最终结果。

[java] view plaincopyprint?
  1. //改进后的程序:   
  2. public class my{   
  3.      public static void main(String[] args){   
  4.          ATM[] pArr=new ATM[100];   
  5.          for(int i=0;i<pArr.length;++i){   
  6.              pArr[i]=new ATM();   
  7.              pArr[i].start();   
  8.          }  
  9.          try{  
  10.              for(int i=0;i<pArr.length;++i){  
  11.                  pArr[i].join();  
  12.              }  
  13.          }catch(InterruptedException e){  
  14.              e.printStackTrace();  
  15.          }  
  16.          System.out.println("Final amount="+ATM.m_acc.m_amount);   
  17.      }   
  18.      static class Account{   
  19.          int m_amount;   
  20.          String m_name;   
  21.          Account(int m,String name){   
  22.              m_amount=m;   
  23.              m_name  =name;   
  24.          }   
  25.          void Deposit(int m){   
  26.              try{   
  27.                  synchronized(this){  
  28.                      int a=m_amount;   
  29.                      a+=m;   
  30.                      Thread.sleep(10);   
  31.                      m_amount=a;   
  32.                  }  
  33.              }catch(InterruptedException e){   
  34.                  e.printStackTrace();   
  35.              }   
  36.          }   
  37.          synchronized void WithDraw(int m){   
  38.              try{   
  39.                  synchronized(this){  
  40.                      int a=m_amount;   
  41.                      a-=m;   
  42.                      Thread.sleep(10);   
  43.                      m_amount=a;   
  44.                  }  
  45.              }catch(InterruptedException e){   
  46.                  e.printStackTrace();   
  47.              }   
  48.          }   
  49.      }   
  50.      static class ATM extends Thread{   
  51.          static Account m_acc=new my.Account(10,"self");   
  52.          public void run(){   
  53.              m_acc.Deposit(1);   
  54.              m_acc.WithDraw(1);   
  55.          }   
  56.      }   
  57. }   

        相比较而言,C++在C++11标准之前,线程同步依赖于操作系统的调用,非常麻烦,像posix系统就必须借助于Pthread线程库:

[cpp] view plaincopyprint?
  1. #include <iostream>   
  2. #include <pthread.h>   
  3. #include <unistd.h>   
  4. using namespace std;  
  5. pthread_cond_t cond  =PTHREAD_COND_INITIALIZER;  
  6. pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;  
  7. void * start_routine(void* pvArg)  
  8. {  
  9.     char* pch=(char*)pvArg;  
  10.     pthread_mutex_lock(&mutex);  
  11.     pthread_cond_wait(&cond,&mutex);  
  12.     pthread_mutex_unlock(&mutex);  
  13.     cout << pch <<endl;  
  14.     cout.widen("jjjj");  
  15.     return NULL;  
  16. }  
  17.   
  18. int main()  
  19. {  
  20.     pthread_t thread;  
  21.     pthread_create(&thread,NULL,start_routine,(void*)"kkk");  
  22.     sleep(5);  
  23.     pthread_mutex_lock(&mutex);  
  24.     pthread_cond_signal(&cond);  
  25.     pthread_mutex_unlock(&mutex);  
  26.     pthread_cond_destroy(&cond);  
  27.     pthread_mutex_destroy(&mutex);  
  28.     pthread_join(thread,NULL);  
  29.     return 0;  
  30. }  

        而且Pthread里面的mutex和conditional还不是正交的,而windows下的mutex和event是正交的。C++11从boost里面引入了atom/thread库,情况终于有所改观。

原创粉丝点击