方法/ 作用
wait: 线程自动释放占有的对象锁,并等待notify。
notify: 随机唤醒一个正在wait当前对象的线程,并让被唤醒的线程拿到对象锁
notifyAll: 唤醒所有正在wait当前对象的线程,但是被唤醒的线程会再次去竞争对象锁。因为一次只有一个线程能拿到锁,所有其他没有拿到锁的线程会被阻塞。推荐使用。
Java中规定,在调用这三个方法时,当前线程必须获得对象锁。因此就得配合synchronized关键字来使用。在synchronized拿到对象锁之后,synchronized代码块或者方法中,必定是会持有对象锁的,因此就可以使用wait()或者notify()。
常用范式:
syn(object) {
//业务逻辑,改变条件
object.notify()/notifyAll()
}
使用wait()、notify()来实现一个生产者、消费者模式:
public class ProductAndCusumer {
private static LinkedList<String> queue = new LinkedList<>(); //需要将queue作为多线程操作的锁
public static final int MAX_CAPACITY = 5;
public static class Producter extends Thread {
@Override
public void run() {
while(true) {
synchronized (queue) {
if (queue.size() >= MAX_CAPACITY) {
Log.i(TAG, "队列已满");
try {
queue.wait(); //停止生产产品,此时在生产者的线程中,调用queue.wait主动去释放锁,让当前消费线程进入等待唤醒去拿锁
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
//可以生产数据
String product = "生产:" + Thread.currentThread().getName();
queue.add(product);
Log.i(TAG, product);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
queue.notifyAll(); //唤醒所有线程拿锁
}
}
}
}
public static class Consumer extends Thread {
@Override
public void run() {
while(true) {
synchronized (queue) {
if (queue.isEmpty()) {
Log.i(TAG, "队列为空");
try {
queue.wait(); //通知生产者生产数据
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
//可以消费数据
Log.i(TAG, "消费:" + queue.pop());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
queue.notifyAll();
}
}
}
}
}
调用:
Producter().start()
Consumer().start()
打印过程:
生产:Thread-5
生产:Thread-5
消费:生产:Thread-5
消费:生产:Thread-5
队列为空
生产:Thread-5
生产:Thread-5
生产:Thread-5
生产:Thread-5
生产:Thread-5
队列已满
消费:生产:Thread-5
消费:生产:Thread-5
消费:生产:Thread-5
消费:生产:Thread-5
消费:生产:Thread-5
队列为空
生产:Thread-5
生产:Thread-5
生产:Thread-5
生产:Thread-5
生产:Thread-5
队列已满
消费:生产:Thread-5
消费:生产:Thread-5
消费:生产:Thread-5
消费:生产:Thread-5
消费:生产:Thread-5
队列为空
生产:Thread-5
生产:Thread-5
生产:Thread-5
生产:Thread-5
锁池、等待池
锁池:某个对象的锁已被线程A拥有,其他线程要执行该对象的 synchronized 方法获取锁时就会进入该对象的锁池,锁池中的线程会去竞争该对象的锁
等待池:某个线程调用了某个对象的 wait 方法,该线程就会释放该对象的锁,进入该对象的等待池,等待池中的线程不会去竞争该对象的锁
调用 notify 会随机唤醒等待池中的一个线程,唤醒后会进入到锁池
调用 notifyAll 会唤醒等待池中的所有线程,唤醒后会都进入到锁池
如何让两个线程循环交替打印数字
使用Object的wait和notify实现
public class StrangePrinter {
Object odd = new Object(); // 奇数条件锁
Object even = new Object(); // 偶数条件锁
private int max;
private AtomicInteger status = new AtomicInteger(1); // AtomicInteger保证可见性,也可以用volatile
public StrangePrinter(int max) {
this.max = max;
}
public class MyPrinter implements Runnable {
private String name;
private int type; // 打印的类型,0:代表打印奇数,1:代表打印偶数
public MyPrinter(String name, int type) {
this.name = name;
this.type = type;
}
@Override
public void run() {
if (type == 1) {
while (status.get() <= max) { // 打印奇数
if (status.get() % 2 == 0) { // 如果当前为偶数,则等待
synchronized (odd) {
try {
odd.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} else {
Log.i(TAG, name + " - " + status.getAndIncrement()); // 打印奇数
synchronized (even) { // 通知偶数打印线程
even.notify();
}
}
}
} else {
while (status.get() <= max) { // 打印偶数
if (status.get() % 2 != 0) { // 如果当前为奇数,则等待
synchronized (even) {
try {
even.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} else {
Log.i(TAG, name + " - " + status.getAndIncrement()); // 打印偶数
synchronized (odd) { // 通知奇数打印线程
odd.notify();
}
}
}
}
}
}
}
调用:
val strangePrinter = StrangePrinter(20)
val executorService = Executors.newFixedThreadPool(2)
executorService.submit(strangePrinter.MyPrinter("Printer1", 0))
executorService.submit(strangePrinter.MyPrinter("Printer2", 1))
executorService.shutdown()
打印结果:
Printer2 - 1
Printer1 - 2
Printer2 - 3
Printer1 - 4
Printer2 - 5
Printer1 - 6
Printer2 - 7
Printer1 - 8
Printer2 - 9
Printer1 - 10
Printer2 - 11
Printer1 - 12
Printer2 - 13
Printer1 - 14
Printer2 - 15
Printer1 - 16
Printer2 - 17
Printer1 - 18
Printer2 - 19
Printer1 - 20
参考: https://www.jianshu.com/p/2286499b4774