java资源竞争问题(线程互斥)

来源:互联网 发布:仿720云全景源码 编辑:程序博客网 时间:2024/04/29 10:23
资源竞争 (线程互斥) 
1、什么是资源竞争 
  有这样一种资源,在某一时刻只能被一个线程所使用:比如打印机、某个文件等等,如果多个线程不加控制的同时使用这类资源,必然会导至错误。 
  下面的例子模拟了一个打印机,多个线程不加控制的同时使用这个打印机: 
Java代码  收藏代码
  1. public class Printer  
  2. {  
  3.     public void print(int printer, String content)  
  4.     {  
  5.         System.out.println("Start working for [" +printer+"]");  
  6.         Thread.yield();  
  7.         System.out.println("===================");  
  8.         Thread.yield();  
  9.         System.out.println(content);  
  10.         Thread.yield();  
  11.         System.out.println("===================");  
  12.         Thread.yield();  
  13.         System.out.println("Work complete for [" +printer+"]\n");  
  14.     }  
  15.       
  16.     public static void main(String[] args)  
  17.     {  
  18.         Printer p = new Printer();  
  19.           
  20.         for (int i=0; i<3; i++)  
  21.             new Thread(new MyThread(p)).start();  
  22.     }  
  23. }  
  24.   
  25. class MyThread implements Runnable  
  26. {  
  27.     private static int counter = 0;  
  28.     private final int id = counter++;  
  29.       
  30.     private Printer printer;  
  31.       
  32.     public MyThread(Printer printer)  
  33.     {  
  34.         this.printer = printer;  
  35.     }  
  36.       
  37.     @Override  
  38.     public void run()  
  39.     {  
  40.         printer.print(id, "Content of " + id);  
  41.     }  
  42.       
  43. }  

  输出结果(sample) 
Output代码  收藏代码
  1. Start working for [0]  
  2. Start working for [1]  
  3. ===================  
  4. ===================  
  5. Start working for [2]  
  6. Content of 0  
  7. Content of 1  
  8. ===================  
  9. ===================  
  10. ===================  
  11. Content of 2  
  12. Work complete for [0]  
  13.   
  14. Work complete for [1]  
  15.   
  16. ===================  
  17. Work complete for [2]  

  从结果可以看到,打印机的输出完全乱套了,各个线程想要打印的内容全部参杂在一起了。 


2、解决资源竞争问题 
  原则上要解决这类问题并不难,只需要一个锁的机制。任何线程在使用打印机前必须先对打印机上锁;在使用完打印机后释放锁;如果线程尝试对打印机上锁时别的线程已经上了锁,则该线程必须等待别的线程先释放锁。 
  Java中,解决上述资源共享类的问题是通过关键字synchronized实现的。java中的对象都有一个‘锁’,这样,任何一个线程尝试访问对象的synchronized方法时,必须要先获得对象的'锁',否则必须等待。 
  一个对象可能会有多个synchronized方法,比如synchronized a()方法和synchronized b()方法。当一个线程获得了对象的锁,进行a()方法、或b()方法了,那么在线程释放该对象的锁之前,别的线程是不能访问该对象的其它synchronized方法的。 
  下面例子是之前的例子的改良版本,只需要简单的把Printer对象的print方法定义成synchronized的就可以达到我们的要求了: 

Java代码  收藏代码
  1. public class Printer  
  2. {  
  3.     public synchronized void print(int printer, String content)  
  4.     {  
  5.         System.out.println("Start working for [" +printer+"]");  
  6.         Thread.yield();  
  7.         System.out.println("===================");  
  8.         Thread.yield();  
  9.         System.out.println(content);  
  10.         Thread.yield();  
  11.         System.out.println("===================");  
  12.         Thread.yield();  
  13.         System.out.println("Work complete for [" +printer+"]\n");  
  14.     }  
  15.       
  16.     public static void main(String[] args)  
  17.     {  
  18.         Printer p = new Printer();  
  19.           
  20.         for (int i=0; i<3; i++)  
  21.             new Thread(new MyThread(p)).start();  
  22.     }  
  23. }  
  24.   
  25. class MyThread implements Runnable  
  26. {  
  27.     private static int counter = 0;  
  28.     private final int id = counter++;  
  29.       
  30.     private Printer printer;  
  31.       
  32.     public MyThread(Printer printer)  
  33.     {  
  34.         this.printer = printer;  
  35.     }  
  36.       
  37.     @Override  
  38.     public void run()  
  39.     {  
  40.         printer.print(id, "Content of " + id);  
  41.     }  
  42.       
  43. }  

  输出结果 
Output代码  收藏代码
  1. Start working for [0]  
  2. ===================  
  3. Content of 0  
  4. ===================  
  5. Work complete for [0]  
  6.   
  7. Start working for [2]  
  8. ===================  
  9. Content of 2  
  10. ===================  
  11. Work complete for [2]  
  12.   
  13. Start working for [1]  
  14. ===================  
  15. Content of 1  
  16. ===================  
  17. Work complete for [1]  

  从结果的输出可以看出来,被模拟的打印机资源在某一时刻,仅被一个线程所使用。 


3、临界区 
  有些时候,你可能不需要隔离整个方法,而只需要隔离方法中的部分代码,这部分被隔离的代码就叫做临界区。临界区中的代码在某一时刻,只能被一个线程访问。 
  下面的例子,是用临界区的方式实现了前面的例子: 

Java代码  收藏代码
  1. public class Printer  
  2. {  
  3.     public void print(int printer, String content)  
  4.     {  
  5.         synchronized(this)  
  6.         {  
  7.             System.out.println("Start working for [" +printer+"]");  
  8.             Thread.yield();  
  9.             System.out.println("===================");  
  10.             Thread.yield();  
  11.             System.out.println(content);  
  12.             Thread.yield();  
  13.             System.out.println("===================");  
  14.             Thread.yield();  
  15.             System.out.println("Work complete for [" +printer+"]\n");  
  16.         }  
  17.     }  
  18.       
  19.     public static void main(String[] args)  
  20.     {  
  21.         Printer p = new Printer();  
  22.           
  23.         for (int i=0; i<3; i++)  
  24.             new Thread(new MyThread(p)).start();  
  25.     }  
  26. }  
  27.   
  28. class MyThread implements Runnable  
  29. {  
  30.     private static int counter = 0;  
  31.     private final int id = counter++;  
  32.       
  33.     private Printer printer;  
  34.       
  35.     public MyThread(Printer printer)  
  36.     {  
  37.         this.printer = printer;  
  38.     }  
  39.       
  40.     @Override  
  41.     public void run()  
  42.     {  
  43.         printer.print(id, "Content of " + id);  
  44.     }  
  45.       
  46. }  

  可以看到,在Java中临界区也是通过synchronized关键字实现的。在synchronized关键字后面,要传一个对象参数,任何线程要进入临界区时必须先要获得该对象的锁,退出临界区时要释放该对象的锁,这样别的线程才有机会进入临界区。 
  从上面两个例子可以看出,临界区和synchronized方法,其原理都是一样的,都是通过在对象上加锁来实现的,只不过临界区来得更加灵活,因为它不光可以对this对象加锁,也可以对任何别的对象加锁。 


4、Lock 
  Java1.5提供了一个显示加锁的机制,比起synchronized方式来说,显示加锁的方法可能让代码看上去更加复杂,但是也带来了更好的灵活性。 
  下面的例子,用Lock的机制实现了前面的例子: 

Java代码  收藏代码
  1. public class Printer  
  2. {  
  3.     private Lock lock = new ReentrantLock();  
  4.       
  5.     public void print(int printer, String content)  
  6.     {  
  7.         lock.lock();  
  8.           
  9.         try  
  10.         {  
  11.             System.out.println("Start working for [" +printer+"]");  
  12.             Thread.yield();  
  13.             System.out.println("===================");  
  14.             Thread.yield();  
  15.             System.out.println(content);  
  16.             Thread.yield();  
  17.             System.out.println("===================");  
  18.             Thread.yield();  
  19.             System.out.println("Work complete for [" +printer+"]\n");  
  20.         }  
  21.         finally  
  22.         {  
  23.             lock.unlock();  
  24.         }  
  25.     }  
  26.       
  27.     public static void main(String[] args)  
  28.     {  
  29.         Printer p = new Printer();  
  30.           
  31.         for (int i=0; i<3; i++)  
  32.             new Thread(new MyThread(p)).start();  
  33.     }  
  34. }  
  35.   
  36. class MyThread implements Runnable  
  37. {  
  38.     private static int counter = 0;  
  39.     private final int id = counter++;  
  40.       
  41.     private Printer printer;  
  42.       
  43.     public MyThread(Printer printer)  
  44.     {  
  45.         this.printer = printer;  
  46.     }  
  47.       
  48.     @Override  
  49.     public void run()  
  50.     {  
  51.         printer.print(id, "Content of " + id);  
  52.     }  
  53.       
  54. }  

  使用Lock的时候,必须要注意两点: 
  • 锁的释放必须放在finally块里面,以保证锁被正确的释放;
  • 如果被隔间的方法或临界间需要返回一个值,那么return语句应该放在try块中,从而不至于使unlock发生得过早而导至错误的发生。

使用显示的Lock机制,可以让程序更加的灵活。比如上面的例子中,如果尝试使用打印机的时候,打印机正被别的线程所使用,那么早取消本次打印。要实现这样的功能,使用synchronized可能不太容易实现,但是使用Lock机制的话,就非常简单了: 

Java代码  收藏代码
  1. public class Printer  
  2. {  
  3.     private Lock lock = new ReentrantLock();  
  4.       
  5.     public void print(int printer, String content)  
  6.     {  
  7.         boolean isLocked = lock.tryLock();  
  8.           
  9.         if (!isLocked)  
  10.             return;  
  11.           
  12.         try  
  13.         {  
  14.             System.out.println("Start working for [" +printer+"]");  
  15.             Thread.yield();  
  16.             System.out.println("===================");  
  17.             Thread.yield();  
  18.             System.out.println(content);  
  19.             Thread.yield();  
  20.             System.out.println("===================");  
  21.             Thread.yield();  
  22.             System.out.println("Work complete for [" +printer+"]\n");  
  23.         }  
  24.         finally  
  25.         {  
  26.             if(isLocked)  
  27.                 lock.unlock();  
  28.         }  
  29.     }  
  30.       
  31.     public static void main(String[] args)  
  32.     {  
  33.         Printer p = new Printer();  
  34.           
  35.         for (int i=0; i<3; i++)  
  36.             new Thread(new MyThread(p)).start();  
  37.     }  
  38. }  
  39.   
  40. class MyThread implements Runnable  
  41. {  
  42.     private static int counter = 0;  
  43.     private final int id = counter++;  
  44.       
  45.     private Printer printer;  
  46.       
  47.     public MyThread(Printer printer)  
  48.     {  
  49.         this.printer = printer;  
  50.     }  
  51.       
  52.     @Override  
  53.     public void run()  
  54.     {  
  55.         printer.print(id, "Content of " + id);  
  56.     }  
  57.       
  58. }  

  Lock.tryLock()方法尝试对lock对象加锁并返回一个boolean值,如果成功了,返回true,表明当前没有别的线程在使用打印机,那么当前线程将获得lock对象的锁,并继续打印;如果失败了,返回false,表明别的线程正在使用打印机,当前线程将简单的返回,而不是等待别的线程释放锁。

0 0