容器.jpg

List

CopyOnWriteArrayList

写时复制,add时加锁
添加效率慢,读取速率快

Set

Queue

BlockingQueue

put: 满了就阻塞住
take:没了就阻塞住

PriorityQueue

DelayQueue

按时间进行任务调度
基于PriorityQueue实现

  1. public class T07_DelayQueue {
  2. static BlockingQueue<MyTask> tasks = new DelayQueue<>();
  3. static Random r = new Random();
  4. static class MyTask implements Delayed {
  5. String name;
  6. long runningTime;
  7. MyTask(String name, long rt) {
  8. this.name = name;
  9. this.runningTime = rt;
  10. }
  11. @Override
  12. public int compareTo(Delayed o) {
  13. if(this.getDelay(TimeUnit.MILLISECONDS) < o.getDelay(TimeUnit.MILLISECONDS))
  14. return -1;
  15. else if(this.getDelay(TimeUnit.MILLISECONDS) > o.getDelay(TimeUnit.MILLISECONDS))
  16. return 1;
  17. else
  18. return 0;
  19. }
  20. @Override
  21. public long getDelay(TimeUnit unit) {
  22. return unit.convert(runningTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
  23. }
  24. @Override
  25. public String toString() {
  26. return name + " " + runningTime;
  27. }
  28. }
  29. public static void main(String[] args) throws InterruptedException {
  30. long now = System.currentTimeMillis();
  31. MyTask t1 = new MyTask("t1", now + 1000);
  32. MyTask t2 = new MyTask("t2", now + 2000);
  33. MyTask t3 = new MyTask("t3", now + 1500);
  34. MyTask t4 = new MyTask("t4", now + 2500);
  35. MyTask t5 = new MyTask("t5", now + 500);
  36. tasks.put(t1);
  37. tasks.put(t2);
  38. tasks.put(t3);
  39. tasks.put(t4);
  40. tasks.put(t5);
  41. System.out.println(tasks);
  42. for(int i=0; i<5; i++) {
  43. System.out.println(tasks.take());
  44. }
  45. }
  46. }

SynchronousQueue

两线程间传递数据

  1. public class T08_SynchronusQueue { //容量为0
  2. public static void main(String[] args) throws InterruptedException {
  3. BlockingQueue<String> strs = new SynchronousQueue<>();
  4. new Thread(()->{
  5. try {
  6. System.out.println(strs.take());
  7. } catch (InterruptedException e) {
  8. e.printStackTrace();
  9. }
  10. }).start();
  11. strs.put("aaa"); //阻塞等待消费者消费
  12. //strs.put("bbb");
  13. //strs.add("aaa");
  14. System.out.println(strs.size());
  15. }
  16. }

TransferQueue -> LinkedTransferQueue


多线程间传递数据

  1. public class T09_TransferQueue {
  2. public static void main(String[] args) throws InterruptedException {
  3. LinkedTransferQueue<String> strs = new LinkedTransferQueue<>();
  4. new Thread(() -> {
  5. try {
  6. System.out.println(strs.take());
  7. } catch (InterruptedException e) {
  8. e.printStackTrace();
  9. }
  10. }).start();
  11. strs.transfer("aaa");
  12. //strs.put("aaa");
  13. /*new Thread(() -> {
  14. try {
  15. System.out.println(strs.take());
  16. } catch (InterruptedException e) {
  17. e.printStackTrace();
  18. }
  19. }).start();*/
  20. }
  21. }