今天刷面经看到有人被问到手撕生产者消费者,所以顺手写一下熟悉一下流程
public class ProducerAndConsumer {
private static final ReentrantLock lock = new ReentrantLock();
private static final Condition empty = lock.newCondition(), full = lock.newCondition();
private static volatile int cnt = 0;
private static final int N = 10;
private static final int MAX_CNT = 30;
private static void add() {
cnt++;
}
private static void get() {
cnt--;
}
public static void main(String[] args) {
Thread[] cons = new Thread[10], pros = new Thread[10];
for (int i = 0; i < N * 100; i++) {
new Thread(() -> {
lock.lock();
try {
while (cnt == 0) {
empty.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("[ CONSUMER " + Thread.currentThread().getName() + " ] => Now cnt = "
+ cnt + ", Then cnt-- = " + (cnt - 1));
get();
full.signal();
lock.unlock();
}).start();
new Thread(() -> {
lock.lock();
try {
while (cnt == MAX_CNT) {
full.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("\033[1;31m[ PRODUCER " + Thread.currentThread().getName() + " ] => Now cnt = "
+ cnt + ", Then ++cnt = " + (cnt + 1) + "\033[0m");
add();
empty.signal();
lock.unlock();
}).start();
}
}
}
线程交替打印模型
public class ThreadDo {
private static volatile int idx = 0;
private static volatile boolean st = false;
private static Object lock = new Object();
private static Thread t1, t2;
private static void sync() {
idx = 0;
t1 = new Thread(() -> {
while (idx < 30) {
synchronized (lock) {
if (idx % 2 == 0) {
System.out.println("[ " + Thread.currentThread().getName() + " ] => Now idx = " + idx + ", ++idx = " + ++idx);
}
}
}
});
t2 = new Thread(() -> {
while (idx < 30) {
synchronized (lock) {
if (idx % 2 == 1) {
System.out.println("\033[1;31m[ " + Thread.currentThread().getName() + " ] => Now idx = " + idx + ", ++idx = " + ++idx + "\033[0m");
}
}
}
});
t1.start();
t2.start();
}
private static void booleanCor() {
idx = 0;
t1 = new Thread(() -> {
while (idx < 30) {
if (!st) {
System.out.println("\033[1;31m[ " + Thread.currentThread().getName() + " ] => Now idx = " + idx + ", ++idx = " + ++idx + "\033[0m");
st = true;
}
}
});
t2 = new Thread(() -> {
while (idx < 30) {
if (st) {
System.out.println("[ " + Thread.currentThread().getName() + " ] => Now idx = " + idx + ", ++idx = " + ++idx);
st = false;
}
}
});
t1.start(); t2.start();
}
public static void main(String[] args) {
booleanCor();
sync();
}
}