Java并发学习之十四——使用Lock同步代码块

淡淡的烟草味﹌ 2022-08-12 01:59 279阅读 0赞

本文是学习网络上的文章时的总结,感谢大家无私的分享。

Java提供另外的机制用来同步代码块。它比synchronized关键字更加强大、灵活。Lock 接口比synchronized关键字提供更多额外的功能。在使用Lock时需要注意的是要释放Lock锁。

  1. package chapter2;
  2. import java.util.concurrent.locks.Lock;
  3. import java.util.concurrent.locks.ReentrantLock;
  4. /*
  5. * 打印队列
  6. */
  7. public class PrintQueue {
  8. private final Lock queueLock = new ReentrantLock();
  9. public void printJob(Object document){
  10. queueLock.lock();//获取Lock对象的控制权
  11. try {
  12. Long duration = (long)(Math.random()*10000);
  13. System.out.println(Thread.currentThread().getName()
  14. +"PrintQueue:Printing a Job during "
  15. +(duration/1000)+" seconds");
  16. Thread.sleep(duration);
  17. } catch (Exception e) {
  18. e.printStackTrace();
  19. } finally{
  20. queueLock.unlock();//释放Lock对象的控制
  21. }
  22. }
  23. }
  24. package chapter2;
  25. public class Job implements Runnable{
  26. private PrintQueue printQueue;
  27. public Job(PrintQueue printQueue){
  28. this.printQueue = printQueue;
  29. }
  30. @Override
  31. public void run() {
  32. System.out.printf("%s:Going to print a document\n",
  33. Thread.currentThread().getName());
  34. printQueue.printJob(new Object());
  35. System.out.printf("%s:The document has been printed\n",Thread.currentThread().getName());
  36. }
  37. }
  38. package chapter2;
  39. /**
  40. *
  41. * <p>
  42. * Description: 使用Lock同步代码块
  43. * </p>
  44. * @author zhangjunshuai
  45. * @version 1.0
  46. * Create Date: 2014-9-16 下午4:57:06
  47. * Project Name: Java7Thread
  48. *
  49. * <pre>
  50. * Modification History:
  51. * Date Author Version Description
  52. * -----------------------------------------------------------------------------------------------------------
  53. * LastChange: $Date:: $ $Author: $ $Rev: $
  54. * </pre>
  55. *
  56. */
  57. public class Main5 {
  58. /**
  59. * <p>
  60. * </p>
  61. * @author zhangjunshuai
  62. * @date 2014-9-16 下午4:57:00
  63. * @param args
  64. */
  65. public static void main(String[] args) {
  66. PrintQueue printQueue = new PrintQueue();
  67. Thread thread[] = new Thread[10];
  68. for(int i=0;i<10;i++){
  69. thread[i] = new Thread(new Job(printQueue),"Thread"+i);
  70. }
  71. for(int i=0;i<10;i++){
  72. thread[i].start();
  73. }
  74. }
  75. }

发表评论

表情:
评论列表 (有 0 条评论,279人围观)

还没有评论,来说两句吧...

相关阅读