Java内置锁的简单认识

多线程开发离不开锁机制,现在的Java语言中,提供了2种锁,一种是语言特性提供的内置锁,还有一种是 java.util.concurrent.locks 包中的锁,这篇文章简单整理一下内置锁的知识点。

内置锁在Java语言中的表现:

多线程的锁,其实本质上就是给一块内存空间的访问添加访问权限,因为Java中是没有办法直接对某一块内存进行操作的,又因为Java是面向对象的语言,一切皆对象,所以具体的表现就是某一个对象承担锁的功能,每一个对象都可以是一个锁。内置锁,使用方式就是使用 synchronized 关键字,synchronized 方法或者 synchronized 代码块。

每一种 synchronized 写法的锁是哪个对象:

1、指定当前对象加锁:

    private synchronized void function() {
//TODO execute something
}

2、指定当前类的Class对象加锁:

    private static synchronized void function() {
//TODO execute something
}

注意此处的 static 关键字。

3、指定任意对象加锁:

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) {
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");
} 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();
}
}
}

1、static synchronized 方法 和 synchronized (MyClass.class) {} 同步代码块的锁都加在
MyClass.class 对象上面:

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 代码块的。

2、非 static 的 synchronized 方法和 synchronized (this) {} 同步代码块的锁都加在当前对象上面:

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 代码块的。

3、当锁加在 MyClass.class 、 this 、 任意对象,这三种情况,起不到任何同步作用:

    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

说明当锁没有加在同一个对象上的时候,起不到线程间的同步作用。

Object中对内置锁进行操作的一些方法:

wait()系列:

wait()系列方法的作用是:使当前已经获得该对象锁的线程进入等待状态,并且释放该对象的锁。

notify()系列:

notify()系列方法的作用是:唤醒那些正在等待该对象锁的线程,使其继续运行。

基于wait() notify()机制,我们可以实现一个简易的生产者-消费者模型。

大体思路如下,一个生产者线程负责向一个仓库中存放(put)物品,一个消费者线程负责从仓库中取出(get)物品。

代码如下:

public class Warehouse {

    private Queue<Integer> 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 : 5  , queue -> [5]
消费者-01 , get : 5 , queue -> []
生产者-01 , put : 7 , queue -> [7]
消费者-01 , get : 7 , queue -> []
生产者-01 , put : 9 , queue -> [9]
生产者-01 , put : 7 , queue -> [9, 7]
消费者-01 , get : 9 , queue -> [7]
生产者-01 , put : 0 , queue -> [7, 0]
生产者-01 , put : 5 , queue -> [7, 0, 5]
消费者-01 , get : 7 , queue -> [0, 5]
生产者-01 , put : 9 , queue -> [0, 5, 9]
生产者-01 , put : 6 , queue -> [0, 5, 9, 6]
消费者-01 , get : 0 , queue -> [5, 9, 6]
生产者-01 , put : 4 , queue -> [5, 9, 6, 4]
生产者-01 , put full wait
消费者-01 , get : 5 , queue -> [9, 6, 4]
生产者-01 , put : 6 , queue -> [9, 6, 4, 6]
生产者-01 , put full wait
消费者-01 , get : 9 , queue -> [6, 4, 6]
生产者-01 , put : 2 , queue -> [6, 4, 6, 2]
生产者-01 , put full wait
消费者-01 , get : 6 , queue -> [4, 6, 2]
生产者-01 , put : 9 , queue -> [4, 6, 2, 9]
生产者-01 , put full wait
消费者-01 , get : 4 , queue -> [6, 2, 9]
生产者-01 , put : 7 , queue -> [6, 2, 9, 7]
生产者-01 , put full wait
消费者-01 , get : 6 , queue -> [2, 9, 7]
生产者-01 , put : 2 , queue -> [2, 9, 7, 2]
上一篇:linux工程管理工具make入门


下一篇:CSS之浮动那些事