目录
一、Lock接口的认识
- 一、Lock接口的认识
- 二、Lock接口中的方法
- 三、Lock和Synchronized的区别
- 四、多个线程获取值案例(没有使用同步的情况)
- 五、多个线程获取值案例(使用Lock接口的情况)
- Lock需要显示地获取和释放锁,繁琐能让代码更灵活。
- 使用Lock可以方便的实现公平性。
- Synchronized不需要显示地获取和释放锁,简单。
- java.util.concurrent.locks包下的Lock接口
- lock() 表示获取锁。
- unlock() 表示释放锁。
- lockInterruptibly() 表示能被中断的获取锁。并且抛出InterruptedException异常。
- tryLock() 表示非阻塞获取锁,如果锁被获取返回true,否则返回false。
- 都是可重入锁。
- Lock需要显示地获取和释放锁,繁琐,当能让代码更灵活。
- Synchronized不需要显示地获取和释放锁,简单。
- Lock是接口,是代码层面的实现,Synchronized是关键字,是依赖JVM实现。
1、代码
package com.xz.thread.t8;
/**
* @description:
* @author: xz
*/
public class Sequeue {
private int value;
public int getValue(){
return value++;
}
public static void main(String[] args) {
Sequeue sequeue = new Sequeue();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" "+sequeue.getValue());
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while(true){
System.out.println(Thread.currentThread().getName()+" "+sequeue.getValue());
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while(true){
System.out.println(Thread.currentThread().getName()+" "+sequeue.getValue());
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
}
}
2、输出结果 3、结论
- 在没有使用同步的情况下,同一个实例中多个线程获取的值存在重复值的情况。
1、代码
package com.xz.thread.t8;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @description:
* @author: xz
*/
public class Sequeue {
private int value;
//所有的线程公用一把锁,所有需要放getValue方法外
Lock lock=new ReentrantLock();
public int getValue(){
lock.lock();//获取锁
int a= value++;
lock.unlock();//释放锁
return a;
}
public static void main(String[] args) {
Sequeue sequeue = new Sequeue();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" "+sequeue.getValue());
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while(true){
System.out.println(Thread.currentThread().getName()+" "+sequeue.getValue());
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while(true){
System.out.println(Thread.currentThread().getName()+" "+sequeue.getValue());
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
}
}
2、输出结果
3、结论
- 在使用Lock接口的情况下,同一个实例中多个线程获取的值不存在重复值的情况。