多线程开发离不开锁机制,现在的Java语言中,提供了2种锁,一种是语言特性提供的内置锁,还有一种是 java.util.concurrent.locks 包中的锁,这篇文章简单整理一下内置锁的知识点。
多线程的锁,其实本质上就是给一块内存空间的访问添加访问权限,因为Java中是没有办法直接对某一块内存进行操作的,又因为Java是面向对象的语言,一切皆对象,所以具体的表现就是某一个对象承担锁的功能,每一个对象都可以是一个锁。
内置锁,使用方式就是使用 synchronized 关键字,synchronized 方法或者 synchronized 代码块。
private synchronized void function() {
//TODO execute something
}
private static synchronized void function() {
//TODO execute something
}
注意此处的 static 关键字。
private void function() {
synchronized (object) {
//TODO execute something
}
}
此时,这段同步代码块的锁加在object对象上面。该对象可以是当前对象(object == this),也可以是当前类的Class对象(object == MyClass.class)。
public class SynchronizedTest {
private Object lock = new Object();
public void synchronizedBlockOnObject(long executeTime) {
// lock对象锁
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + " -> start synchronizedBlockOnObject");
doSomething(executeTime);
System.out.println(Thread.currentThread().getName() + " -> end synchronizedBlockOnObject");
}
}
public void synchronizedBlockOnThis(long executeTime) {
// 当前实例对象锁
synchronized (this) {
System.out.println(Thread.currentThread().getName() + " -> start synchronizedBlockOnThis");
doSomething(executeTime);
System.out.println(Thread.currentThread().getName() + " -> end synchronizedBlockOnThis");
}
}
public void synchronizedBlockOnClass(long executeTime) {
// 类锁
synchronized (SynchronizedTest.class) {
System.out.println(Thread.currentThread().getName() + " -> start synchronizedBlockOnClass");
doSomething(executeTime);
System.out.println(Thread.currentThread().getName() + " -> end synchronizedBlockOnClass");
}
}
// 非静态方法,当前实例对象锁
public synchronized void synchronizedMethodOnThis(long executeTime) {
System.out.println(Thread.currentThread().getName() + " -> start synchronizedMethodOnThis");
doSomething(executeTime);
System.out.println(Thread.currentThread().getName() + " -> end synchronizedMethodOnThis");
}
// 静态方法,类锁(SynchronizedTest.class)
public static synchronized void synchronizedMethodOnClass(long executeTime) {
System.out.println(Thread.currentThread().getName() + " -> start synchronizedMethodOnClass");
doSomething(executeTime);
System.out.println(Thread.currentThread().getName() + " -> end synchronizedMethodOnClass");
}
private static void doSomething(long executeTime) {
try {
Thread.sleep(executeTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
SynchronizedTest synchronizedTest = new SynchronizedTest();
new Thread(new Runnable() {
@Override
public void run() {
SynchronizedTest.synchronizedMethodOnClass(3000);
}
}, "Thread static synchronized method").start();
new Thread(new Runnable() {
@Override
public void run() {
synchronizedTest.synchronizedBlockOnClass(2000);
}
}, "Thread synchronized block on Class").start();
}
运行结果:
Thread static synchronized method -> start synchronizedMethodOnClass
Thread static synchronized method -> end synchronizedMethodOnClass
Thread synchronized block on Class -> start synchronizedBlockOnClass
Thread synchronized block on Class -> end synchronizedBlockOnClass说明当线程 Thread static synchronized method 进入方法 synchronizedMethodOnClass 的时候,线程Thread synchronized block on Class 是不能进入synchronizedBlockOnClass 代码块的。
public static void main(String[] args) {
SynchronizedTest synchronizedTest = new SynchronizedTest();
new Thread(new Runnable() {
@Override
public void run() {
synchronizedTest.synchronizedMethodOnThis(3000);
}
}, "Thread non-static synchronized method").start();
new Thread(new Runnable() {
@Override
public void run() {
synchronizedTest.synchronizedBlockOnThis(2000);
}
}, "Thread synchronized block on this").start();
}
运行结果如下: Thread non-static synchronized method -> start synchronizedMethodOnThis Thread non-static synchronized method -> end synchronizedMethodOnThis Thread synchronized block on this -> start synchronizedBlockOnThis Thread synchronized block on this -> end synchronizedBlockOnThis 说明当线程 Thread non-static synchronized method 进入方法 synchronizedMethodOnThis 的时候,线程Thread synchronized block on this 是不能进入synchronizedBlockOnThis 代码块的。
public static void main(String[] args) {
SynchronizedTest synchronizedTest = new SynchronizedTest();
new Thread(new Runnable() {
@Override
public void run() {
synchronizedTest.synchronizedMethodOnThis(3000);
}
}, "Thread non-static synchronized method").start();
new Thread(new Runnable() {
@Override
public void run() {
SynchronizedTest.synchronizedMethodOnClass(2000);
}
}, "Thread static sybchronized method").start();
new Thread(new Runnable() {
@Override
public void run() {
synchronizedTest.synchronizedBlockOnObject(4000);
}
}, "Thread sybchronized block on other Object").start();
}
运行结果如下:
Thread non-static synchronized method -> start synchronizedMethodOnThis Thread static sybchronized method -> start synchronizedMethodOnClass Thread sybchronized block on other Object -> start synchronizedBlockOnObject Thread static sybchronized method -> end synchronizedMethodOnClass Thread non-static synchronized method -> end synchronizedMethodOnThis Thread sybchronized block on other Object -> end synchronizedBlockOnObject 说明当锁没有加在同一个对象上的时候,起不到线程间的同步作用。
wait()系列方法的作用是:使当前已经获得该对象锁的线程进入等待状态,并且立即释放该对象的锁,等待的到相应的notify重新获得锁后才继续执行。
notify()系列方法的作用是:不会立刻释放锁,而是等到notify所在synchronized代码块全部都执行完以后才会释放锁。
notifyAll() 会通知等待队列中的所有线程。
大体思路如下,一个生产者线程负责向一个仓库中存放(put)物品,一个消费者线程负责从仓库中取出(get)物品。
public class Warehouse {
private Queue queue;
private int capacity;
public Warehouse(int capacity) {
this.capacity = capacity;
queue = new LinkedList();
}
public synchronized void put(int num) {
if (queue.size() >= capacity) {
try {
System.out.println(Thread.currentThread().getName() + " , put full wait");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.add(num);
System.out.println(Thread.currentThread().getName() + " , put : " + num + " , queue -> " + queue);
notifyAll();
}
public synchronized int get() {
if (queue.isEmpty()) {
try {
System.out.println(Thread.currentThread().getName() + " , get empty wait");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int num = queue.poll();
System.out.println(Thread.currentThread().getName() + " , get : " + num + " , queue -> " + queue);
notifyAll();
return num;
}
public static void main(String[] args) {
Warehouse warehouse = new Warehouse(4);
Random random = new Random();
// 简易的生产者、消费者
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
warehouse.put(random.nextInt(10));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "生产者-01").start();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
warehouse.get();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "消费者-01").start();
}
}
运行结果如下:
生产者-01 , put : 3 , queue -> [3]
消费者-01 , get : 3 , queue -> []
生产者-01 , put : 5 , queue -> [5]
消费者-01 , get : 5 , queue -> []
生产者-01 , put : 8 , queue -> [8]
生产者-01 , put : 2 , queue -> [8, 2]
消费者-01 , get : 8 , queue -> [2]
生产者-01 , put : 6 , queue -> [2, 6]
生产者-01 , put : 0 , queue -> [2, 6, 0]
消费者-01 , get : 2 , queue -> [6, 0]
生产者-01 , put : 6 , queue -> [6, 0, 6]
生产者-01 , put : 6 , queue -> [6, 0, 6, 6]
消费者-01 , get : 6 , queue -> [0, 6, 6]
生产者-01 , put : 4 , queue -> [0, 6, 6, 4]
生产者-01 , put full wait
消费者-01 , get : 0 , queue -> [6, 6, 4]
生产者-01 , put : 8 , queue -> [6, 6, 4, 8]
生产者-01 , put full wait
消费者-01 , get : 6 , queue -> [6, 4, 8]
生产者-01 , put : 3 , queue -> [6, 4, 8, 3]
生产者-01 , put full wait
消费者-01 , get : 6 , queue -> [4, 8, 3]
生产者-01 , put : 5 , queue -> [4, 8, 3, 5]
生产者-01 , put full wait
内置锁在进入同步块时,采取的是无限等待的策略,一旦开始等待,就既不能中断也不能取消,容易产生饥饿与死锁的问题。
在线程调用notify方法时,会随机选择相应对象的等待队列的一个线程将其唤醒,而不是按照FIFO(先入先出策略)的方式,如果有强烈的公平性要求,就无法满足。
Synchronized在JDK1.5及之前性能(主要指吞吐率)比较差,扩展性也不如ReentrantLock。但是JDK1.6以后,修改了管理内置锁的算法,使得Synchronized和标准的ReentrantLock性能差别不大。