-
多个atomic类连续调用是否构成原子性?
场景还原:
在Demo2中我们定义一个AtomicInteger类,在test()方法中进行两次原子操作,第一次,判断get()是否小于1000,第二次进行自增。在主线程内创建三个线程,一次执行Demo2中的test()方法。
代码还原:
public class Demo2 {
AtomicInteger count = new AtomicInteger(0);
public void test(){
for(int i = 0;i<1000;i++){
if(count.get() < 1000){
count.incrementAndGet();
}
}
}
public static void main(String[] args) {
Demo2 demo2 = new Demo2();
List<Thread> list =new ArrayList<>();
for(int i = 0;i<3;i++){
list.add(new Thread(demo2::test));
}
list.forEach(o->o.start());
list.forEach(o-> {
try {
o.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println(demo2.count);
}
}
程序执行结果:预期结果应该是1000(不同机器多次执行效果有所不同)
根据结果表明,多个atomic类型连续调用不能构成原子性。
2.实现一个容器,提供两个方法,add,size。写连个线程,线程1添加10个元素到容器中,线程2监控元素个数。当个数到达5个时,线程2给出相应提示并结束线程
场景还原:定义Container类,添加个List成员。并提供add,和size方法。在主线程创建两个线程。线程1负责创建,线程2负责监听。
代码还原1:使用wait和notify
public class Container {
volatile List<Object> list = new ArrayList<>();
public void add(Object o){
list.add(o);
}
public int size(){
return list.size();
}
public static void main(String[] args) {
Container c = new Container();
Object lock = new Object();
new Thread(()->{
synchronized (lock){
System.out.println("线程1启动!");
for(int i = 0;i<=10;i++){
if(c.size() == 5){
lock.notify();
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
c.add(new Object());
System.out.println("add:"+i);
}
System.out.println("线程1结束");
}
}).start();
new Thread(()->{
synchronized (lock){
System.out.println("线程2启动");
if(c.size() != 5){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("线程2:结束:");
lock.notify();
}
}).start();
}
}
执行结果:
技术要点:线程1和线程2,wait和notify的配合使用。
代码还原2:使用CountDownLatch
package com.lqq;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class Container2 {
List<Object> list = new ArrayList<>();
public void add(Object o){
list.add(o);
}
public int size(){
return list.size();
}
public static void main(String[] args) {
Container2 c = new Container2();
Object lock = new Object();
CountDownLatch countDownLatch = new CountDownLatch(1);
new Thread(()->{
synchronized (lock){
System.out.println("线程1启动!");
for(int i = 0;i<=10;i++){
if(c.size() == 5){
countDownLatch.countDown();
}
c.add(new Object());
System.out.println("add:"+i);
}
System.out.println("线程1结束");
}
}).start();
new Thread(()->{
synchronized (lock){
System.out.println("线程2启动");
if(c.size() != 5){
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("线程2:结束:");
}
}).start();
}
}
这种技术和wait和notify相比,代码简洁很多。
3.写一个固定容量同步器,拥有put和get方法,以及getCunt方法。能过支持两个生产者和10个消费者的调用
场景还原:
定义个Contaner类,添加LinkeList成员,MaxCount用来定义最大容量,count用来记录里面还有多少个。
代码实现:wait和notify实现
public class Container<T> {
private final LinkedList<T> list = new LinkedList<>();
private final int MAX_COUNT = 10;
int count = 0;
public synchronized void put(T t){
while(count == MAX_COUNT){
System.out.println("仓库已满!等待消费...");
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("开始生产...");
list.add(t);
count ++;
this.notifyAll();
}
public synchronized T get() {
T t = null;
while (count == 0){
System.out.println("仓库缺货,等待生产...");
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("开始消费...");
t = this.list.removeFirst();
count --;
this.notifyAll();
return t;
}
public static void main(String[] args) {
Container container = new Container();
for(int i = 0;i<10;i++){
new Thread(()->{
while (true){
container.get();
}
}).start();
}
for(int i = 0;i<2;i++){
new Thread(()->{
while(true){
container.put(new Object());
}
}).start();
}
}
}
代码2:ReentrantLock实现
public class Container2<T> {
private final LinkedList<T> list = new LinkedList<>();
private final int MAX_COUNT = 10;
int count = 0;
Lock lock = new ReentrantLock();
Condition producer = lock.newCondition();
Condition consumer = lock.newCondition();
public void put(T t){
try {
lock.lock();
while(count == MAX_COUNT){
System.out.println("仓库已满!等待消费...");
producer.await();
}
System.out.println("开始生产...");
list.add(t);
count ++;
consumer.signalAll();
}catch (Exception e){
}finally {
lock.unlock();
}
}
public T get() {
T t = null;
try {
lock.lock();
while (count == 0){
System.out.println("仓库缺货,等待生产...");
consumer.await();
}
System.out.println("开始消费...");
t = this.list.removeFirst();
count --;
producer.signalAll();
}catch (Exception e){
}finally {
lock.unlock();
}
return t;
}
public static void main(String[] args) {
Container2 container = new Container2();
for(int i = 0;i<10;i++){
new Thread(()->{
while (true){
container.get();
}
}).start();
}
for(int i = 0;i<2;i++){
new Thread(()->{
while(true){
container.put(new Object());
}
}).start();
}
}
}
代码实现3:基于LinkedBlockingDeque队列实现
package com.lqq.demo1;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
public class Container3<T> {
private final int MAX_COUNT = 10;
private final BlockingQueue<T> list = new LinkedBlockingDeque<>(MAX_COUNT);
public void put(T t){
boolean offer = list.offer(t);
if(!offer){
System.out.println("仓库已满!等待消费...");
}else{
System.out.println("已生产!");
}
}
public T get() {
T t = null;
t = list.poll();
if(t == null){
System.out.println("仓库缺货,等待生产...");
}else{
System.out.println("已被消费!");
}
return t;
}
public static void main(String[] args) {
Container3 container = new Container3();
for(int i = 0;i<2;i++){
new Thread(()->{
for (int k =0;k<20;k++)
container.put(new Object());
}).start();
}
for(int i = 0;i<10;i++){
new Thread(()->{
for (int k= 0;k<5;k++)
container.get();
}).start();
}
}
}