目标
使用三个线程循环打印ABC 10次
volatile+自旋
/**
* @author wxl
* 建立三个线程A、B、C,A线程打印10次字母A,B线程打印10次字母B,C线程打印10次字母C,
* 但是要求三个线程同时运行,并且实现交替打印,即按照ABCABCABC的顺序打印。
*/
public class MyThread extends Thread {
volatile static int state;
private int type;
static HashMap<Integer, Character> map = new HashMap() {
{
put(0, 'A');
put(1, 'B');
put(2, 'C');
}
};
MyThread(int type) {
this.type = type;
}
@Override
public void run() {
int i = 0;
while (i < 10) {
if (state % 3 == type) {
System.out.print(map.get(state % 3));
state++;
i++;
}
}
}
}
class Test {
public static void main(String[] args) {
MyThread t0 = new MyThread(0);
MyThread t1 = new MyThread(1);
MyThread t2 = new MyThread(2);
t0.start();
t1.start();
t2.start();
}
}
synchronized+wait+notify
package com.laixiw.demo.juc;
import java.util.HashMap;
/**
* @author wxl
*/
public class Test2 {
private Object lock = new Object();
private final int count = 10;
private final int threadCount = 3;
private volatile int state = 0;
private static HashMap<Integer, Character> map = new HashMap() {{
put(0, 'A');
put(1, 'B');
put(2, 'C');
}};
public void printABC(int type) {
for (int i = 0; i < count; i++) {
synchronized (lock) {
while (state % threadCount != type) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " " + map.get(type));
state++;
lock.notifyAll();
}
}
}
public static void main(String[] args) {
Test2 test2 = new Test2();
Thread t1 = new Thread(() ->
test2.printABC(0)
);
Thread t2 = new Thread(() ->
test2.printABC(1)
);
Thread t3 = new Thread(() ->
test2.printABC(2)
);
t1.start();
t2.start();
t3.start();
}
}
wait和notify的使用
关于wait和notify的使用,wait的使用一般搭配的不是if而是while,notify一般不使用,而是使用notifyAll()
notify()函数是随机通知一个,所以可能会出现其他线程满足条件也会在等待,因此一般使用notifyAll(),也是由于使用的是notifyAll(),因此被唤醒的线程可能并不满足条件,所以需要使用while循环来确保确实是满足退出等待的条件才可以。
另外,使用notify可能会造成死锁,下面介绍一下。
在一个生产者消费者模型中(如下面代码),两个生产者,两个消费者,库存为1,生产者生产的库存到达1时,停止生产,消费者在库存为0时,停止消费,初始时库存为0,考虑下面这一种情况,两个消费者同时去消费,被synchronized加锁,第一个生产者生产完成之后,调用notify(),唤醒了消费者一(注意,唤醒之后还要重新抢占锁),此时,线程生产者二抢占到了锁,进去之后发现库存满了,需要wait(),然后消费者一获得了锁,(现在库存为1,消费者二和和生产者二进行wait(),消费者一开始运行),消费者一消费完成之后,notify(),随机notify到消费者二,消费者二发现没有物品,重新等待,也就出现了死锁,生产者二和消费者二同时等待对方。
原理
介绍一下里面的原理,JVM会为对象锁维护两个集合,Entry Set(进入synchronized代码块被卡住了)和Wait Set(锁对象.wait()进入这个队列),分别对应着线程的BLOCKED和WAITING状态,当对象锁被释放时,JVM会唤醒处于Entry Set中的某一个线程,这个线程的状态就从BLOCKED转变为RUNNABLE。当对象的notify()方法被调用时,JVM会唤醒处于Wait Set中的某一个线程,这个线程的状态就从WAITING转变为RUNNABLE。,每当对象的锁被释放后,那些所有处于RUNNABLE状态的线程会共同去竞争获取对象的锁,最终会有一个线程获取到对象的锁,而其他竞争失败的线程继续在Entry Set中等待下一次机会。
public void produce() {
synchronized (this) {
while (mBuf.isFull()) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
mBuf.add();
// notify出错
notifyAll();
}
}
public void consume() {
synchronized (this) {
while (mBuf.isEmpty()) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
mBuf.remove();
notifyAll();
}
}
await+signal
使用ReentrantLock中的condation来实现精准的阻塞和唤醒
package com.laixiw.demo.juc;
import java.util.HashMap;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author wxl
*/
public class Test3 {
ReentrantLock lock = new ReentrantLock();
Condition condition0 = lock.newCondition();
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
private final int count = 10;
private final int threadCount = 3;
private volatile int state = 0;
private static HashMap<Integer, Character> map = new HashMap() {{
put(0, 'A');
put(1, 'B');
put(2, 'C');
}};
void printABC(int type, Condition current, Condition next) {
for (int i = 0; i < count; i++) {
lock.lock();
if (state % 3 != type) {
try {
current.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
state++;
System.out.print(map.get(type));
next.signal();
lock.unlock();
}
}
public static void main(String[] args) {
Test3 test3 = new Test3();
new Thread(() -> {
test3.printABC(0, test3.condition0, test3.condition1);
}).start();
new Thread(() -> {
test3.printABC(1, test3.condition1, test3.condition2);
}).start();
new Thread(() -> {
test3.printABC(2, test3.condition2, test3.condition0);
}).start();
}
}
补充
三个线程打印1-100
/**
* @author wxl
* 三个线程循环打印100
*/
public class MyThread2 extends Thread {
static volatile int state = 1;
int type;
public MyThread2(int type) {
this.type = type;
}
@Override
public void run() {
while (true) {
if (state > 100) {
break;
}
if (state % 3 == type) {
if (state <= 100)
System.out.println(type + " " + state);
state++;
}
}
}
}
class Test2 {
public static void main(String[] args) {
MyThread2 t0 = new MyThread2(1);
MyThread2 t1 = new MyThread2(2);
MyThread2 t2 = new MyThread2(0);
t0.start();
t1.start();
t2.start();
}
}