问题1
实现一个容器,提供两个方法,add,size,写两个线程,线程1添加10个元素到容器中,线程2实现监控元素的个数,当到5个时候,线程2给出提示并结束。
考点:锁的应用wait和notify 以及其他锁的应用
import java.util.ArrayList;
import java.util.List;
public class TaobaoTest {
public static void main(String[] args) {
Container container = new Container();
Object lock = new Object();
new Thread(() -> {
synchronized (lock) {
System.out.println("t2启动");
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("判断是第五个打印");
lock.notify();
}
return;
},"t2").start();
new Thread(() -> {
synchronized (lock) {
System.out.println("t1启动");
try {
for (int i = 0; i < 10; i++) {
if (container.size() == 5) {
lock.notify();
System.out.println("叫t1打印");
lock.wait();
}
container.add("a");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"t1").start();
}
}
/**
* 容器
*/
class Container {
private volatile List<String> list = new ArrayList<>();
public void add(String a) {
list.add(a);
}
public int size() {
return list.size();
}
}
问题2 写一个固定容量的同步容器,拥有put和get方法,以及getcount方法,能够支持2个生产者以及10个消费者阻塞调用
使用ReentrantLock的Condition来实现生产着消费者
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class TaobaoTest03 {
public static void main(String[] args) {
Box box = new Box();
List<Thread> threadList = new ArrayList<>();
//两个生产者
for (int i = 0; i < 2; i++) {
threadList.add(new Thread(() -> {
int j = 0;
Thread t = Thread.currentThread();
String name = t.getName();
for (int k = 0; k < 50; k++) {
try {
box.put(j);
System.out.println(name + "线程put数字" + j);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "put" + i));
}
//十个消费者
for (int i = 0; i < 10; i++) {
threadList.add(new Thread(() -> {
System.out.println("get启动");
Thread t = Thread.currentThread();
String name = t.getName();
for (int j = 0; j < 10; j++) {
try {
System.out.println(name + "线程get到数字" + box.get());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "get" + i));
}
//启动所有
threadList.forEach((o) -> o.start());
}
}
class Box {
private final Queue<Integer> bigBox = new LinkedList<>();
Lock lock = new ReentrantLock();
Condition producer = lock.newCondition();
Condition consumer = lock.newCondition();
private int count = 0;
private final int MAX = 10;
public Integer get() throws InterruptedException {
lock.lock();
//如果数量不够了,直接进入等待队列
while (count == 0) {
//判断count是否是0是0就停止消费
consumer.await();
System.out.println("生产满了停止了" );
}
Integer get = bigBox.poll();
++count;
producer.signalAll();
lock.unlock();
return get;
}
public void put(Integer integer) throws InterruptedException {
lock.lock();
while (count == MAX) {
producer.await();
System.out.println("消费完了停止了" );
}
--count;
bigBox.offer(integer);
consumer.signalAll();
lock.unlock();
}
}