首页 技术 正文
技术 2022年11月14日
0 收藏 662 点赞 2,958 浏览 5642 个字

参考:http://www.dewen.net.cn/q/9077

   http://coolxing.iteye.com/blog/1236909

lock,tryLock,lockInterruptibly

分别对应无限制锁,定时锁(通过while可以作为轮询锁),可中断锁。

Lock接口的 线程请求锁的 几个方法:

lock(), 拿不到lock就不罢休,不然线程就一直block。 比较无赖的做法。
tryLock(),马上返回,拿到lock就返回true,不然返回false。 比较潇洒的做法。
带时间限制的tryLock(),拿不到lock,就等一段时间,超时返回false。比较聪明的做法。

下面的lockInterruptibly()就稍微难理解一些。

先说说线程的打扰机制,每个线程都有一个 打扰 标志。这里分两种情况,
1. 线程在sleep或wait,join, 此时如果别的进程调用此进程的 interrupt()方法,此线程会被唤醒并被要求处理InterruptedException;(thread在做IO操作时也可能有类似行为,见java thread api)
2. 此线程在运行中, 则不会收到提醒。但是 此线程的 “打扰标志”会被设置, 可以通过isInterrupted()查看并作出处理。

lockInterruptibly()和上面的第一种情况是一样的, 线程在请求lock并被阻塞时,如果被interrupt,则“此线程会被唤醒并被要求处理InterruptedException”。

E.G.  lock() & lockInterruptibly()

–lock()

 package lockInterruptibly; import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock; public class MyService { public ReentrantLock lock = new ReentrantLock();
private Condition condition = lock.newCondition(); public void waitMethod() {
try {
lock.lock();
// lock.lockInterruptibly();
System.out.println("lock begin " + Thread.currentThread().getName());
for (int i = 0; i < 100000000; i++) {
String newString = new String();
Math.random();
// System.out.println(i + " ");
}
System.out.println("lock end " + Thread.currentThread().getName());
} finally {
if (lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
} }
 package lockInterruptibly; public class Run {     public static void main(String[] args) {
try {
final MyService service = new MyService();
Runnable runnable = new Runnable() { @Override
public void run() {
// TODO Auto-generated method stub
service.waitMethod();
}
};
Thread a = new Thread(runnable);
a.setName("A");
a.start();
Thread b = new Thread(runnable);
b.setName("B");
b.start();
Thread.sleep(500);
b.interrupt();
System.out.println("main end");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }

Thread–lock,lockInterruptibly,tryLock,tryLock(long timeout, TimeUnit unit)

正如lock()拿不到锁誓不罢休,线程b并未响应interrupt,一直在等待着锁。

–lockInterruptibly()

 package lockInterruptibly; import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock; public class MyService { public ReentrantLock lock = new ReentrantLock();
private Condition condition = lock.newCondition(); public void waitMethod() {
try {
// lock.lock();
lock.lockInterruptibly();
System.out.println("lock begin " + Thread.currentThread().getName());
for (int i = 0; i < 100000000; i++) {
String newString = new String();
Math.random();
// System.out.println(i + " ");
}
System.out.println("lock end " + Thread.currentThread().getName());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
} }
 package lockInterruptibly; public class Run {     public static void main(String[] args) {
try {
final MyService service = new MyService();
Runnable runnable = new Runnable() { @Override
public void run() {
// TODO Auto-generated method stub
service.waitMethod();
}
};
Thread a = new Thread(runnable);
a.setName("A");
a.start();
Thread b = new Thread(runnable);
b.setName("B");
b.start();
Thread.sleep(500);
b.interrupt();
System.out.println("main end");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }

Thread–lock,lockInterruptibly,tryLock,tryLock(long timeout, TimeUnit unit)

线程b并没有拿到锁,此时调用interrupt方法,则线程b被唤醒并被要求处理InterruptedException,即抛出了InterruptedException

当然,线程b也并不会执行了

但是当线程b拿到锁执行时才调用interrupt,这时候线程b并不会中断

tryLock() & tryLock(long, TimeUnit)

|–void lock(): 执行此方法时, 如果锁处于空闲状态, 当前线程将获取到锁. 相反, 如果锁已经被其他线程持有, 将禁用当前线程, 直到当前线程获取到锁.

|–boolean tryLock(): 如果锁可用, 则获取锁, 并立即返回true, 否则返回false. 该方法和lock()的区别在于, tryLock()只是”试图”获取锁, 如果锁不可用, 不会导致当前线程被禁用, 当前线程仍然继续往下执行代码. 而lock()方法则是一定要获取到锁, 如果锁不可用, 就一直等待, 在未获得锁之前,当前线程并不继续向下执行. 通常采用如下的代码形式调用tryLock()方法:

|–boolean tryLock(long timeout, TimeUnit unit):如果锁定在给定等待时间内没有被另一个线程保持,且当前线程未被中断,则获取该锁定。

通常采用如下的代码形式调用tryLock()方法:

    Lock lock = new ReentrantLock();
if (lock.tryLock()) {
try {
// manipulate protected state
} finally {
lock.unlock();
}
} else {
// perform alternative actions
}

此用法可确保如果获取了锁, 则会释放锁; 如果未获取锁, 则不会试图将其释放.

–tryLock()

 package tryLock.copy.copy; import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock; /**
* boolean tryLock(long timeout, TimeUnit unit) 如果锁定在给定等待时间内没有被另一个线程保
* 持,且当前线程未被中断,则获取该锁定
*
* @author MicroCat
*
*/
public class MyService { public ReentrantLock lock = new ReentrantLock(); public void waitMethod() {
if (lock.tryLock()) {
try {
System.out.println(Thread.currentThread().getName() + " 获得锁");
for (int i = 0; i < 10000; i++) {
if (i % 100 == 0) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
} finally {
lock.unlock();
}
} else {
System.out.println(Thread.currentThread().getName() + " 没有获得锁");
}
} }
 package tryLock.copy.copy; public class Run {     public static void main(String[] args) throws InterruptedException {
final MyService service = new MyService();
Runnable runnable = new Runnable() { @Override
public void run() {
service.waitMethod();
}
};
Thread a = new Thread(runnable);
a.setName("A");
a.start();
Thread b = new Thread(runnable);
b.setName("B");
b.start();
} }

Thread–lock,lockInterruptibly,tryLock,tryLock(long timeout, TimeUnit unit)

线程b没有获得锁,a线程执行完也没有继续执行

–tryLock(long, TimeUnit)

 package tryLock.copy.copy.copy; import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock; /**
* boolean tryLock(long timeout, TimeUnit unit) 如果锁定在给定等待时间内没有被另一个线程保
* 持,且当前线程未被中断,则获取该锁定
*
* @author MicroCat
*
*/
public class MyService { public ReentrantLock lock = new ReentrantLock(); public void waitMethod() {
try {
if (lock.tryLock(3, TimeUnit.SECONDS)) {
try {
System.out.println(Thread.currentThread().getName() + " 获得锁");
for (int i = 0; i < 10000; i++) {
if (i % 100 == 0) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
} finally {
lock.unlock();
}
} else {
System.out.println(Thread.currentThread().getName() + " 没有获得锁");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }
 package tryLock.copy.copy.copy; public class Run {     public static void main(String[] args) throws InterruptedException {
final MyService service = new MyService();
Runnable runnable = new Runnable() { @Override
public void run() {
service.waitMethod();
}
};
Thread a = new Thread(runnable);
a.setName("A");
a.start();
Thread b = new Thread(runnable);
b.setName("B");
b.start();
} }

在给定时间内各线程都有拿到锁,所以线程a,b都有执行

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,144
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,615
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,458
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,234
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,869
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,950