ARTS-第24周

ARTS (第24周)

这不知道是我第几次感叹了,积累很重要。
本周:并行算法

Algorithm 算法

并行算法(广度优先算法)

但是这里的线程部分最好使用线程池。毕竟开启新线程需要额外花费资源。

而且如果需要的操作并不多,并行算法未必有意义。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package algorithm.senior.parallel;

import java.util.LinkedList;
import java.util.concurrent.LinkedBlockingQueue;

public class ParallelTest {

public static void main(String[] args) {
int deep = 10;
int base = 0;
int base2 = 100;
Node root = new Node(-1);
for (int i = 0; i < deep; i++) {
Node node = new Node(base++);
root.c.add(node);
for (int j = 0; j < deep; j++) {
node.c.add(new Node(base2++));
}
}
System.out.println(root);
paralleBfs(root);
}

public static void paralleBfs(Node root) {

LinkedBlockingQueue<Node> q1 = new LinkedBlockingQueue<>();
LinkedBlockingQueue<Node> q2 = new LinkedBlockingQueue<>();
// 根节点全部放入队列1
q1.add(root);

while (!q1.isEmpty() || !q2.isEmpty()) {
deal(q1, q2);
//交换
LinkedBlockingQueue<Node> temp = q1;
q1 = q2;
q2 = temp;
}
}

private static void deal(LinkedBlockingQueue<Node> q1, LinkedBlockingQueue<Node> q2) {
System.out.print("deal->");
int s = 5;// n个线程
// 计数器 用于计算是否全部线程的计算已经结束
Counter c = new Counter(s);
for (int i = 0; i < s; i++) {
new Thread(new Runnable() {
public void run() {
Node n = q1.poll();
while (n != null) {
// 操作
System.out.print(n.v + " ");
for (Node node : n.c) {
q2.add(node);
}
n = q1.poll();
}
c.subCounter();
}
}).start();
}
// 处理结束
while (c.getCounter() > 0) {
System.out.println("->"+c.getCounter());
}
System.out.println("end");
return;
}

// 计数器
static class Counter {
int counter;

public int getCounter() {
return counter;
}

// 防止线程安全问题 这里就直接加个synchronized锁 也可以用lock或者cas等
public synchronized void subCounter() {
counter--;
}

public Counter(int c) {
this.counter = c;
}
}
//节点
static class Node {
Node() {
}

Node(int v) {
this.v = v;
}

int v;
LinkedList<Node> c = new LinkedList<>();

@Override
public String toString() {
return "{" + v + ",c:[" + c + "]}";
}

}
}

Review 英文文章

https://docs.spring.io/spring-security/oauth/apidocs/index.html

spring 各类API介绍 (英文)

Tip 技巧

极客时间的专栏《数据结构与算法之美》

本周学习了该专栏中的下50-52篇

索引:索引就像是一个字典的页码,可以通过索引快速查找到自己想要的东西。

并行算法:当一些逻辑没有先后关系的时候,就可以多线程来处理。提高效率。当然最好还是得用线程池,否则开启新线程的时间可能更大。

redis:核心思路就是:压缩列表、数组、链表、散列表、跳表。

Share 分享

https://docs.spring.io/spring-security/oauth/apidocs/index.html

spring 各类API介绍 (英文)