Java中的线程--并发库中的集合

时间:2023-03-08 22:24:35
Java中的线程--并发库中的集合

  线程中的知识点基本都已经学完了,看看Java5并发库中提供的集合。。。

一、可堵塞队列

队列包含固定长度的队列和不固定长度的队列

ArrayBlockQueue中只有put()方法和take()方法才具有阻塞功能

1、阻塞队列的功能和效果,代码如下:

 import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue; /**
* @className: BlockingQueueTest
* @description: 可阻塞队列的应用
* @author: ssc
* @date: 2019年6月22日 上午11:07:22
*/
public class BlockingQueueTest { public static void main(String[] args) {
BlockingQueue queue = new ArrayBlockingQueue(3);
for (int i = 0; i < 2; i++) {
new Thread() {
@Override
public void run() {
while (true) {
try {
Thread.sleep((long) (Math.random() * 10000));
System.out.println(Thread.currentThread().getName() + "准备放数据");
// 往对列中放数据
queue.put(1);
System.out.println(Thread.currentThread().getName() + "已经放了数据,队列目前有" + queue.size() + "个数据");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}.start();
} new Thread() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(10000);
System.out.println(Thread.currentThread().getName() + "准备取数据");
// 从队列中取出数据
queue.take();
System.out.println(Thread.currentThread().getName() + "已经取走数据,队列目前有" + queue.size() + "个数据");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}.start(); } }

2、堵塞队列来实现通知的功能

代码示例如下:

 import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue; public class Business { private BlockingQueue<Integer> queue1 = new ArrayBlockingQueue<Integer>(1);
private BlockingQueue<Integer> queue2 = new ArrayBlockingQueue<Integer>(1); // 这种写法是匿名构造方法 它在构造方法中优先级是最高的,所有构造方法之前首先执行
{
try {
queue2.put(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void sub(int i) { try {
// 队列1 要放入值
queue1.put(1);
for (int j = 1; j <= 10; j++) {
System.out.println("sub thread sequece of " + j + ", loop of " + i);
}
// 队列2 要把值取出来
queue2.take(); } catch (InterruptedException e) {
e.printStackTrace();
}
} public void main(int i) {
try {
queue2.put(1);
for (int j = 1; j <= 100; j++) {
System.out.println("main thread sequece of " + j + ", loop of " + i);
}
queue1.take();
} catch (InterruptedException e) {
e.printStackTrace();
} }
}

二、同步集合(并发集合)类

传统集合在并发访问时是有问题的

Java5中提供了一些同步集合类:

ConcurrentMap

CopyOnWriteArrayList

CopyOnWriteArraySet

就是这些集合类是线程安全的,即使在多线程的环境下,也不会存在并发问题,用法是和基本的集合类是一样的,只不过JDK中实现了线程同步的代码!!!