Java多线程之 Lock接口和ReentrantLock的使用

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

在多线程开发中,除了synchronized这个关键字外,我们还能通过Lock接口来实现这种效果。通过Lock接口来实现

这种多线程加锁效果的好处是非常的灵活,我们不在需要对整个函数加锁,而且可以很方便的把他放在我们函数的任何

一个地方,非常的称心,而且从效率上来说,使用Lock接口要比使用synchronized关键字效率高一些,下面我们来使用

一个例子来说明这种方法的使用。


package com.bird.concursey.charpet3;public class Job implements Runnable private PrintQueue printQueue; public Job(PrintQueue printQueue) {  this.printQueue = printQueue; } @Override public void run() {  System.out.printf("%s: Going to print a document\n", Thread    .currentThread().getName());  printQueue.printJob(new Object());  System.out.printf("%s: The document has been printed\n", Thread    .currentThread().getName()); }}


package com.bird.concursey.charpet3;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class PrintQueue {  private final Lock queueLock = new ReentrantLock();  public void printJob(Object document) {  queueLock.lock();  Long duration=(long)(Math.random() * 10000);  System.out.println(Thread.currentThread().getName()+ ":PrintQueue: Printing a Job during "+(duration/1000)+" seconds");  try {   Thread.sleep(duration);  } catch (InterruptedException e) {   e.printStackTrace();  }finally{   queueLock.unlock();  } }  public static void main(String[] args) {  PrintQueue printQueue = new PrintQueue();  Thread thread[] = new Thread[10];  for(int i = 0; i < 10; i++) {   thread[i] = new Thread(new Job(printQueue), "Thread " + i);  }  for(int i = 0; i < 10; i++) {   thread[i].start();  } }}


           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow
这里写图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值