如果想让变量在多个线程间可见,可以使用volatile关键字。
线程间通信:
wait 让当前线程等待 释放锁
notify 唤醒其他线程 不释放锁
使用wait/notify 模拟 Queue
=========================================================================================================================
package com.bjsxt.base.conn008;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class Queue {
private LinkedList<Object> list = new LinkedList<>();
private AtomicInteger count = new AtomicInteger(0);
private int minSize = 0;
private int maxSize ;
//初始化一个对象,用于加锁
private Object lock = new Object();
public Queue(int maxSize){
this.maxSize = maxSize;
}
/**
* 向集合中加入元素
* @param object
*/
public void put(Object object){
synchronized (lock) {
while(count.get() == this.maxSize){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.add(object);
count.incrementAndGet();//自增1
System.out.println("新加入的元素为:" + object + "当前共有元素个数:" +list.size());
lock.notify();//唤醒另一个线程
}
}
public Object take(){
Object ret = null;
synchronized (lock) {
while(count.get() == this.minSize){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
ret = list.removeFirst();
count.decrementAndGet();//自减1
System.out.println("移除了一个元素:" + ret +"当前共有元素个数:" + getSize());
lock.notify();
}
return ret;
}
public int getSize(){
int len = this.count.get();
return len;
}
public static void main(String[] args) {
final Queue queue = new Queue(5);
queue.put("a");
queue.put("b");
queue.put("c");
queue.put("d");
queue.put("e");
System.out.println("当前容器的长度为:" + queue.getSize());
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
queue.put("f");
queue.put("g");
}
});
thread1.start();
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
queue.take();
}
});
thread2.start();
}
}
==============================================================================================================================
这个小程序模拟的是阻塞有界队列。