线程池
//线程池 -- 》 Executors.newFixedThreadPoo() 获取线程池
ExecutorService es = Executors.newFixedThreadPool(2);
Runnable r1 = new Runnable() {
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("###"+i);
}
}
};
Runnable r2 = new Runnable() {
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("$$$"+i);
}
}
};
Runnable r3 = new Runnable() {
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("***"+i);
}
}
};
//向线程池中提交任务对象
es.submit(r1);
es.submit(r2);
es.submit(r3);
//销毁线程池
es.shutdown();
callable接口
有返回值的线程任务对象,定义的泛型决定call()方法返回值类型
ExecutorService es = Executors.newFixedThreadPool(2);
Callable<Integer> r1 = new Callable<Integer>() {
public Integer call() throws Exception {
return 10+20;
}
};
es.submit(r1);
Future接口
Future<Integer> f1 = es.submit(r1);
Future<Integer> f2 = es.submit(r2);
Integer i1 = f1.get();
Integer i2 = f2.get();
生产者消费者模式
public class TestMyStack {
public static void main(String[] args) throws InterruptedException {
MyStack ms = new MyStack();
//A - 》 push
Runnable r1 = new Runnable() {
public void run() {
for(char c='a';c<='z';c++) {
//循环的添加
ms.push(c);
}
}
};
//B - > pop
Runnable r2 = new Runnable() {
public void run() {
for(int i=0;i<26;i++) {
//循环的删除
ms.pop();
}
}
};
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
t1.join();
t2.join();
}
}
class MyStack{
private char[] cs = new char[6];
private int index;
//入栈
public synchronized void push(char c) {
//如果长度到达限制 则陷入等待
while(cs.length==index) {
try {
//生产者陷入等待
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(c+" push ");
//添加一个元素
cs[index] = c;
print();
index++;
//唤醒修消费者
this.notifyAll();
}
//出栈
public synchronized void pop() {
//如果元素为0 则陷入等待
while(index<=0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
index--;
System.out.print(cs[index]+" pop ");
//移除一个元素
cs[index] = 0;
print();
//唤醒生产者
this.notifyAll();
}
//遍历
public void print() {
for (char c : cs) {
System.out.print(c);
}
System.out.println();
}
}
线程安全的集合类
BlockingQueue(集合接口)
阻塞队列 实现了生产者消费者模式
offer(E e):
添加一个元素 ,如果没有可用的元素,则陷入等待
take():
移除一个元素,若集合内容为空,则陷入无限期等待
poll():
同上 陷入有限期的等待
实现类
ArrayBlockingQueue
数组实现 有界队列 做添加操作时有可能陷入等待
LinkedBlockingQueue
链表实现 无界队列 做添加操作时不会陷入等待
CopyOnWriteArrayList
: 在原数组的基础上,复制一份数据;在做写操作时,在复制的数组上来做。在牺牲写操作效率的基础上,提高了读效率
读操作多,写操作少时使用
CopyOnWriteArraySet
: Set的实现类,原理同CopyWriteArrayList
ConcurrentHashMap
:
JDK5.0 - JDK 7.0 使用分段锁,对每一段进行加锁;当访问同一段时,才会互斥。
JDK 8.0 开始 使用CAS算法 无锁
总结
有颜色的是 线程安全的集合类
蓝色 - JDK 1.5
绿色 - JDK 1.0
黄色 - 接口