answer) {
29 | if (0 >= sum || 0 >= n) {
30 | return;
31 | }
32 |
33 | // 找到一组解,直接输出
34 | if (sum == n) {
35 | for (Integer num : answer) {
36 | System.out.print(num + " ");
37 | }
38 | System.out.println(n);
39 | }
40 |
41 | answer.add(n);
42 | sumOfKNumber(sum - n, n - 1, answer);
43 | answer.remove(answer.size() - 1);
44 | sumOfKNumber(sum, n - 1, answer);
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/algorithm/tmop/Solution011.java:
--------------------------------------------------------------------------------
1 | package algorithm.tmop;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc: 最大连续子数组和
6 | * 时间复杂度: O(n)
7 | * 空间复杂度: O(1)
8 | * @date:
9 | */
10 | public class Solution011 {
11 |
12 | public static void main(String[] args) {
13 | int[] array = {1, -2, 3, 10, -4, 7, 2, -5};
14 |
15 | System.out.println(maxSubArray(array));
16 | }
17 |
18 | public static int maxSubArray(int[] array) {
19 | if (null == array || 0 >= array.length) {
20 | return 0;
21 | }
22 |
23 | // 以前一位置元素结尾的最大连续子数组的和
24 | int preSum = 0;
25 | // 最大连续子数组的和
26 | int maxSum = array[0];
27 | for (int i = 0; i < array.length; ++i) {
28 | if (0 <= preSum) {
29 | preSum += array[i];
30 | } else {
31 | preSum = array[i];
32 | }
33 |
34 | if (preSum > maxSum) {
35 | maxSum = preSum;
36 | }
37 | }
38 |
39 | return maxSum;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/algorithm/tmop/Solution012.java:
--------------------------------------------------------------------------------
1 | package algorithm.tmop;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc: 跳台阶问题
6 | * 时间复杂度: O(n)
7 | * 空间复杂度: O(1)
8 | * @date:
9 | */
10 | public class Solution012 {
11 |
12 | public static void main(String[] args) {
13 | System.out.println(climbStairs(5));
14 | }
15 |
16 | /**
17 | * 初始化指定 dp[0]=1 dp[1]=1(1台阶有1种走法), 则 n 台阶总共有dp[n]种走法
18 | * @param n
19 | * @return
20 | */
21 | public static int climbStairs(int n) {
22 | int[] dp = {1, 1, 2};
23 |
24 | if (1 >= n) {
25 | return 1;
26 | }
27 |
28 | for (int i = 2; i <= n; ++i) {
29 | dp[2] = dp[0] + dp[1];
30 | dp[0] = dp[1];
31 | dp[1] = dp[2];
32 | }
33 |
34 | return dp[2];
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/algorithm/tmop/Solution016.java:
--------------------------------------------------------------------------------
1 | package algorithm.tmop;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc: 完美洗牌算法
6 | * 时间复杂度: O(n)
7 | * 空间复杂度:
8 | * @date:
9 | */
10 | public class Solution016 {
11 |
12 | public static void main(String[] args) {
13 | int[] a = {0, 1, 2, 3, 4, 5, 6, 7, 8};
14 |
15 | locationReplace(a);
16 | }
17 |
18 | /**
19 | * 下标从1开始计数
20 | * a1,a2,a3,a4,b1,b2,b3,b4
21 | * n 为4
22 | * 1.当 i <= n 时, 该元素在新数组中的下标为: 2*i
23 | * 2.当 i > n 时, 该元素在新数组中的下标为: (2*i)%(2*n+1)
24 | *
25 | * @param a
26 | */
27 | public static void locationReplace(int[] a) {
28 | if (null == a || 0 >= a.length) {
29 | return;
30 | }
31 |
32 | int[] b = new int[a.length];
33 | int n = (a.length - 1) >>> 1;
34 | int n2 = n * 2;
35 |
36 | for (int i = 1; i < a.length; ++i) {
37 | if (i <= n) {
38 | b[2 * i] = a[i];
39 | } else {
40 | b[(2 * i) % (n2 + 1)] = a[i];
41 | }
42 | }
43 |
44 | for (int num : b) {
45 | System.out.print(num + " ");
46 | }
47 | }
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/src/main/java/algorithm/tmop/Solution017.java:
--------------------------------------------------------------------------------
1 | package algorithm.tmop;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc: 二叉树的最近公共祖先
6 | * @date: 2018/12/02
7 | */
8 | public class Solution017 {
9 |
10 | /**
11 | * 在root为根的二叉树中找A,B的LCA:
12 | * 如果找到了就返回这个LCA
13 | * 如果只碰到A,就返回A
14 | * 如果只碰到B,就返回B
15 | * 如果都没有,就返回null
16 | *
17 | * @param root
18 | * @param p
19 | * @param q
20 | * @return
21 | */
22 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
23 | if (null == root || p == root || q == root) {
24 | return root;
25 | }
26 |
27 | TreeNode left = lowestCommonAncestor(root.left, p, q);
28 | TreeNode right = lowestCommonAncestor(root.right, p, q);
29 | if (null != left && null != right) {
30 | return root;
31 | }
32 |
33 | return null != left ? left : right;
34 | }
35 |
36 | private static class TreeNode {
37 | int val;
38 | TreeNode left;
39 | TreeNode right;
40 |
41 | TreeNode(int x) {
42 | val = x;
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/algorithm/tmop/Solution018.java:
--------------------------------------------------------------------------------
1 | package algorithm.tmop;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc: 有序数组的查找
6 | * 时间复杂度: O(logN)
7 | * 空间复杂度: O(1)
8 | * @date:
9 | */
10 | public class Solution018 {
11 |
12 | public static void main(String[] args) {
13 | int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
14 | final int target = 8;
15 | System.out.println("target=" + target + "的下标为:" + binarySearch(array, target));
16 | }
17 |
18 | /**
19 | * 对于有序数组,首选二分查找.
20 | * 找到元素则返回该元素的下标,未找到则返回-1
21 | *
22 | * @param array
23 | * @param target
24 | * @return
25 | */
26 | public static int binarySearch(int[] array, int target) {
27 | if (null == array || 0 >= array.length) {
28 | return -1;
29 | }
30 |
31 | int left = 0;
32 | int right = array.length - 1;
33 | while (left <= right) {
34 | int middle = left + (right - left) / 2;
35 | if (array[middle] > target) {
36 | right = middle - 1;
37 | } else if (array[middle] < target) {
38 | left = middle + 1;
39 | } else {
40 | return middle;
41 | }
42 | }
43 | return -1;
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/algorithm/tmop/Solution019.java:
--------------------------------------------------------------------------------
1 | package algorithm.tmop;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc: 行列递增矩阵的查找
6 | * 时间复杂度: O(m+n)
7 | * 空间复杂度: O(1)
8 | * @date:
9 | */
10 | public class Solution019 {
11 |
12 | public static void main(String[] args) {
13 | int[][] matrix = {
14 | {1, 2, 8, 9},
15 | {2, 4, 9, 12},
16 | {4, 7, 10, 13},
17 | {6, 8, 11, 15}};
18 |
19 | final int target = 6;
20 | System.out.println(matrixSearch(matrix, target));
21 | }
22 |
23 | public static boolean matrixSearch(int[][] matrix, int target) {
24 | if (null == matrix || 0 >= matrix.length) {
25 | return false;
26 | }
27 |
28 | int i = 0;
29 | int j = matrix[0].length - 1;
30 | while (true) {
31 | if (target == matrix[i][j]) {
32 | return true;
33 | } else if (target > matrix[i][j] && i < matrix.length - 1) {
34 | ++i;
35 | } else if (target < matrix[i][j] && j > 0) {
36 | --j;
37 | } else {
38 | return false;
39 | }
40 | }
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/algorithm/tmop/Solution020.java:
--------------------------------------------------------------------------------
1 | package algorithm.tmop;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc: 出现次数超过一半的数
6 | * 时间复杂度: O(n)
7 | * 空间复杂度: O(1)
8 | * @date:
9 | */
10 | public class Solution020 {
11 |
12 | public static void main(String[] args) {
13 | int[] array = {3, 1, 2, 3, 3, 0, 3};
14 |
15 | System.out.println(findNumber(array));
16 | }
17 |
18 | public static int findNumber(int[] array) {
19 | if (null == array || 0 >= array.length) {
20 | return -1;
21 | }
22 |
23 | int number = array[0];
24 | int count = 1;
25 | for (int i = 1; i < array.length; ++i) {
26 | if (array[i] == number) {
27 | ++count;
28 | } else {
29 | if (1 == count) {
30 | number = array[i];
31 | } else {
32 | --count;
33 | }
34 | }
35 | }
36 | return number;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/algorithm/tmop/Solution021.java:
--------------------------------------------------------------------------------
1 | package algorithm.tmop;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc: 最大连续乘积子数组
6 | * 时间复杂度: O(n)
7 | * 空间复杂度: O(1)
8 | * @date:
9 | */
10 | public class Solution021 {
11 |
12 | public static void main(String[] args) {
13 | double[] array = {-2.5, 4, 0, 3, 0.5, 8, -1};
14 |
15 | System.out.println(maxSubArray(array));
16 | }
17 |
18 | public static double maxSubArray(double[] array) {
19 | if (null == array || 0 >= array.length) {
20 | return 0.0D;
21 | }
22 |
23 | double ans = array[0];
24 | double maxEnd = array[0];
25 | double minEnd = array[0];
26 | for (int i = 1; i < array.length; ++i) {
27 | // 当前数字为正数时,以其结尾的最大乘积子数组来自于之前的最大
28 | // 当前数字为负数时,以其结尾的最大乘积子数组来自于之前的最小
29 | double end1 = maxEnd * array[i];
30 | double end2 = minEnd * array[i];
31 | maxEnd = Math.max(array[i], Math.max(end1, end2));
32 | minEnd = Math.min(array[i], Math.min(end1, end2));
33 |
34 | ans = Math.max(ans, maxEnd);
35 | }
36 | return ans;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/bishi/Main0901.java:
--------------------------------------------------------------------------------
1 | package bishi;
2 |
3 | import java.util.HashMap;
4 | import java.util.Scanner;
5 |
6 | /**
7 | * 拼多多
8 | *
9 | * 求循环小数位置和循环体长度
10 | */
11 | public class Main0901 {
12 | public static void main(String[] args) {
13 | Scanner sc = new Scanner(System.in);
14 | int m = sc.nextInt();
15 | int n = sc.nextInt();
16 |
17 | HashMap map = new HashMap<>();
18 | int k = m % n;
19 | int count = 0;
20 | while (map.get(k) == null && k != 0) {
21 | map.put(k, count++);
22 | k *= 10;
23 | k %= n;
24 | }
25 | if (k == 0) {
26 | System.out.println(count + " " + 0);
27 | } else {
28 | System.out.println(map.get(k) + " " + (count - map.get(k)));
29 | }
30 | }
31 | }
--------------------------------------------------------------------------------
/src/main/java/bishi/Main090401.java:
--------------------------------------------------------------------------------
1 | package bishi;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * @author: mayuan
7 | * @desc: 求二进制中1的个数
8 | * @date: 2018/09/04
9 | */
10 | public class Main090401 {
11 | public static void main(String[] args) {
12 | Scanner scanner = new Scanner(System.in);
13 | long number = scanner.nextLong();
14 | long ans = 0;
15 |
16 | while (0 != number) {
17 | ++ans;
18 | number = number & (number - 1);
19 | }
20 | System.out.println(ans);
21 |
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/bishi/Main090402.java:
--------------------------------------------------------------------------------
1 | package bishi;
2 |
3 | import java.util.Arrays;
4 | import java.util.Scanner;
5 |
6 | /**
7 | * @author: mayuan
8 | * @desc:
9 | * @date: 2018/09/04
10 | */
11 | public class Main090402 {
12 | public static void main(String[] args) {
13 | Scanner scanner = new Scanner(System.in);
14 |
15 | int n = Integer.parseInt(scanner.nextLine());
16 | int targetTime = Integer.parseInt(scanner.nextLine());
17 | int[][] matrix = new int[n][3];
18 |
19 | for (int i = 0; i < n; ++i) {
20 | String[] temp = scanner.nextLine().split("\\s+");
21 | matrix[i][0] = Integer.parseInt(temp[0]);
22 | matrix[i][1] = Integer.parseInt(temp[1]);
23 | matrix[i][2] = Integer.parseInt(temp[2]);
24 | }
25 |
26 | Arrays.sort(matrix, (a, b) -> (a[0] - b[0]));
27 |
28 | boolean flag = false;
29 | for (int i = 0; i < n; ++i) {
30 | if (matrix[i][1] <= targetTime && targetTime <= matrix[i][2]) {
31 | flag = true;
32 | System.out.println(matrix[i][0]);
33 | }
34 | }
35 | if (!flag) {
36 | System.out.println("null");
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/bishi/Main090601.java:
--------------------------------------------------------------------------------
1 | package bishi;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * @author: mayuan
7 | * @desc:
8 | * @date: 2018/09/06
9 | */
10 | public class Main090601 {
11 | public static void main(String args[]) {
12 | Scanner scanner = new Scanner(System.in);
13 | int n = Integer.parseInt(scanner.nextLine());
14 |
15 | int[] from = new int[n + 1];
16 | int[] to = new int[n + 1];
17 |
18 | for (int i = 1; i < n; ++i) {
19 | String[] temp = scanner.nextLine().split("\\s+");
20 | int x = Integer.parseInt(temp[0]);
21 | int y = Integer.parseInt(temp[1]);
22 | from[i] = x;
23 | to[i] = y;
24 | }
25 |
26 | if (n <= 4) {
27 | System.out.println(n);
28 | } else {
29 | System.out.println(n + 3);
30 | }
31 |
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/bishi/Main090702.java:
--------------------------------------------------------------------------------
1 | package bishi;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * @author: mayuan
7 | * @desc:
8 | * @date: 2018/09/06
9 | */
10 | public class Main090702 {
11 | public static void main(String args[]) {
12 | Scanner scanner = new Scanner(System.in);
13 | int testNumber = Integer.parseInt(scanner.nextLine());
14 |
15 | while (0 < testNumber--) {
16 | String[] temp = scanner.nextLine().split("\\s+");
17 | int n = Integer.parseInt(temp[0]);
18 | int k = Integer.parseInt(temp[1]);
19 | int leave = n - k;
20 | if (0 == k || n == k) {
21 | System.out.println("0 0");
22 | continue;
23 | }
24 | if (2 >= n) {
25 | System.out.println("0 0");
26 | continue;
27 | }
28 |
29 | int min = 0, max = leave;
30 | if (k <= leave) {
31 | max = k - 1;
32 | }
33 |
34 |
35 | System.out.println(min + " " + max);
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/bishi/Main0909001.java:
--------------------------------------------------------------------------------
1 | package bishi;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | */
7 | public class Main0909001 {
8 | public static void main(String[] args) {
9 | Scanner sc = new Scanner(System.in);
10 | int testNumber = Integer.parseInt(sc.nextLine());
11 |
12 | while (0 < testNumber--) {
13 | int n = sc.nextInt();
14 | int m = sc.nextInt();
15 |
16 | int[][] matrix = new int[m][2];
17 | for (int i = 0; i < m; ++i) {
18 | matrix[i][0] = sc.nextInt();
19 | matrix[i][1] = sc.nextInt();
20 | }
21 |
22 | if (0 == (n + m) % 2) {
23 | System.out.println("NO");
24 | }
25 | System.out.println("YES");
26 | }
27 | }
28 | }
--------------------------------------------------------------------------------
/src/main/java/bishi/Main0909002.java:
--------------------------------------------------------------------------------
1 | package bishi;
2 |
3 | import java.util.Arrays;
4 | import java.util.Scanner;
5 |
6 | /**
7 | */
8 | public class Main0909002 {
9 | public static void main(String[] args) {
10 | Scanner scanner = new Scanner(System.in);
11 | int n = Integer.parseInt(scanner.nextLine());
12 |
13 | int[][] matrix = new int[n][3];
14 | for (int i = 0; i < n; ++i) {
15 | matrix[i][0] = scanner.nextInt();
16 | matrix[i][1] = scanner.nextInt();
17 | matrix[i][2] = scanner.nextInt();
18 | }
19 |
20 | Arrays.sort(matrix, (a, b) -> (a[0] - b[0]));
21 |
22 | int ans = 0;
23 | for (int i = 0; i < n; ++i) {
24 | for (int j = 0; j < n; ++j) {
25 | if ((matrix[i][0] < matrix[j][0]) &&
26 | (matrix[i][1] < matrix[j][1]) &&
27 | (matrix[i][2] < matrix[j][2])) {
28 | ++ans;
29 | break;
30 | }
31 | }
32 | }
33 |
34 | System.out.println(ans);
35 | }
36 | }
--------------------------------------------------------------------------------
/src/main/java/bishi/Main090901.java:
--------------------------------------------------------------------------------
1 | package bishi;
2 |
3 | import java.util.HashSet;
4 | import java.util.Scanner;
5 | import java.util.Set;
6 |
7 | /**
8 | * @author: mayuan
9 | * @desc:
10 | * @date: 2018/09/09
11 | */
12 | public class Main090901 {
13 | public static void main(String args[]) {
14 | Scanner scanner = new Scanner(System.in);
15 |
16 | String str = scanner.nextLine();
17 |
18 | int maxLength = 0;
19 | Set set = new HashSet<>();
20 |
21 | int count = 0;
22 | for (int i = 0; i < str.length(); ++i) {
23 | char c = str.charAt(i);
24 | if (!set.contains(c)) {
25 | set.add(c);
26 | ++count;
27 | if (maxLength < count) {
28 | maxLength = count;
29 | }
30 | } else {
31 | count = 1;
32 | if (maxLength < count) {
33 | maxLength = count;
34 | }
35 | set.clear();
36 | set.add(c);
37 | }
38 | }
39 |
40 | System.out.println(maxLength);
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/java/bishi/Main091601.java:
--------------------------------------------------------------------------------
1 | package bishi;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | */
7 | public class Main091601 {
8 | public static void main(String[] args) {
9 | Scanner scanner = new Scanner(System.in);
10 | int n = Integer.parseInt(scanner.nextLine());
11 | int[] numbers = new int[n];
12 | int[] sum = new int[n];
13 |
14 | for (int i = 0; i < n; ++i) {
15 | numbers[i] = scanner.nextInt();
16 | if (0 != i) {
17 | sum[i] = sum[i - 1] + numbers[i];
18 | } else {
19 | sum[i] = numbers[0];
20 | }
21 | }
22 |
23 | boolean hasAnswer = false;
24 | int max = (numbers[0] > numbers[1]) ? numbers[0] : numbers[1];
25 | for (int i = 2; i < n; ++i) {
26 | max = (numbers[i] > max) ? numbers[i] : max;
27 | if (max < sum[i] - max) {
28 | hasAnswer = true;
29 | System.out.println(i + 1);
30 | break;
31 | }
32 | }
33 |
34 | if (!hasAnswer) {
35 | System.out.println(-1);
36 | }
37 | }
38 | }
--------------------------------------------------------------------------------
/src/main/java/bishi/iqiyi/Main091501.java:
--------------------------------------------------------------------------------
1 | package bishi.iqiyi;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | */
7 | public class Main091501 {
8 | public static void main(String[] args) {
9 | Scanner sc = new Scanner(System.in);
10 |
11 | String[] numbers = sc.nextLine().split("\\s+");
12 | int k = Integer.parseInt(sc.nextLine());
13 |
14 | for (int i = 0; i < numbers.length; i += k) {
15 | reverse(numbers, i, i + k - 1);
16 | }
17 |
18 | for (int i = 0; i < numbers.length; ++i) {
19 | System.out.print(numbers[i] + " ");
20 | }
21 | }
22 |
23 | private static void reverse(String[] strs, int start, int end) {
24 | if (end >= strs.length) {
25 | return;
26 | }
27 |
28 | while (start < end) {
29 | String temp = strs[start];
30 | strs[start] = strs[end];
31 | strs[end] = temp;
32 |
33 | ++start;
34 | --end;
35 | }
36 | }
37 | }
--------------------------------------------------------------------------------
/src/main/java/bishi/iqiyi/Main091502.java:
--------------------------------------------------------------------------------
1 | package bishi.iqiyi;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | */
7 | public class Main091502 {
8 | public static void main(String[] args) {
9 | Scanner sc = new Scanner(System.in);
10 |
11 | int n = Integer.parseInt(sc.nextLine());
12 |
13 | if (n < 5) {
14 | System.out.println(0);
15 | return;
16 | }
17 |
18 | int sum = 0;
19 | int pre = 0;
20 | int current = 0;
21 | for (int i = 5; i <= n; ++i) {
22 | current = pre + countNumberOf5(i);
23 |
24 | sum += current;
25 |
26 | pre = current;
27 | }
28 |
29 | System.out.println(sum);
30 | }
31 |
32 | public static int countNumberOf5(int n) {
33 | int ans = 0;
34 |
35 | if (5 > n || 0 != (n % 5)) {
36 | return ans;
37 | } else {
38 | ++ans;
39 | return ans + countNumberOf5(n / 5);
40 | }
41 | }
42 |
43 | }
--------------------------------------------------------------------------------
/src/main/java/concurrent/CountDownLatchExample.java:
--------------------------------------------------------------------------------
1 | package concurrent;
2 |
3 | import java.util.concurrent.CountDownLatch;
4 | import java.util.concurrent.ExecutorService;
5 | import java.util.concurrent.Executors;
6 |
7 | /**
8 | * @author: mayuan
9 | * @desc: 用来控制一个线程等待多个线程。(某个线程等待多个线程到达)
10 | * 维护了一个计数器 cnt,每次调用 countDown() 方法会让计数器的值减 1,减到 0 的时候,那个因为调用 await() 方法而在等待的线程就会被唤醒。
11 | * @date: 2018/09/14
12 | */
13 | public class CountDownLatchExample {
14 |
15 | public static void main(String[] args) {
16 | final int totalThread = 10;
17 |
18 | CountDownLatch countDownLatch = new CountDownLatch(totalThread);
19 |
20 | ExecutorService executorService = Executors.newCachedThreadPool();
21 | for (int i = 0; i < totalThread; ++i) {
22 | executorService.execute(() -> {
23 | System.out.println("hello CountDownLatch.");
24 | countDownLatch.countDown();
25 | });
26 | }
27 | try {
28 | countDownLatch.await();
29 | } catch (InterruptedException e) {
30 | e.printStackTrace();
31 | }
32 | System.out.println("all come.");
33 | executorService.shutdown();
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt01/TryConcurrency.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt01;
2 |
3 | import java.util.concurrent.TimeUnit;
4 |
5 | /**
6 | * @author: mayuan
7 | * @desc:
8 | * @date: 2018/06/27
9 | */
10 | public class TryConcurrency {
11 | public static void main(String[] args) {
12 | new Thread(TryConcurrency::enjoyMusic).start();
13 | new Thread(TryConcurrency::browseNews).start();
14 | }
15 |
16 | private static void browseNews() {
17 | while (true) {
18 | System.out.println("游览网页中...");
19 | sleep(1);
20 | }
21 | }
22 |
23 | private static void enjoyMusic() {
24 | while (true) {
25 | System.out.println("听音乐中...");
26 | sleep(1);
27 | }
28 | }
29 |
30 | private static void sleep(int seconds) {
31 | if (seconds < 0) {
32 | seconds = 0;
33 | }
34 |
35 | try {
36 | TimeUnit.SECONDS.sleep(seconds);
37 | } catch (InterruptedException e) {
38 | e.printStackTrace();
39 | }
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt02/DaemonThread.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt02;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/06/28
7 | */
8 | public class DaemonThread {
9 |
10 | public static void main(String[] args) throws InterruptedException {
11 | Thread thread = new Thread(() -> {
12 | while (true) {
13 | try {
14 | Thread.sleep(1);
15 | } catch (InterruptedException e) {
16 | e.printStackTrace();
17 | }
18 | }
19 | });
20 | // 守护线程具备自动结束生命周期的特性
21 | thread.setDaemon(true);
22 | thread.start();
23 |
24 | Thread.sleep(2_000L);
25 | System.out.println("Main thread finished lifecycle.");
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt02/ThreadConstruction.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt02;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/06/28
7 | */
8 | public class ThreadConstruction {
9 |
10 | public static void main(String[] args) {
11 | System.out.println(args.length);
12 | System.out.println(args);
13 |
14 |
15 | Thread t1 = new Thread("t1");
16 |
17 | ThreadGroup group = new ThreadGroup("TestGroup");
18 | Thread t2 = new Thread(group, "t2");
19 |
20 | ThreadGroup mainGroup = Thread.currentThread().getThreadGroup();
21 |
22 | System.out.println("Main thread belong to " + mainGroup.getName() + " group.");
23 | System.out.println("t1 thread belong to " + t1.getThreadGroup().getName() + " group.");
24 | System.out.println("t2 thread belong to " + t2.getThreadGroup().getName() + " group.");
25 |
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt03/CurrentThread.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt03;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/06/30
7 | */
8 | public class CurrentThread {
9 | public static void main(String[] args) {
10 | Thread thread = new Thread() {
11 | @Override
12 | public void run() {
13 | System.out.println("当前线程名:" + Thread.currentThread().getName());
14 | System.out.println(Thread.currentThread() == this);
15 | }
16 | };
17 | thread.start();
18 |
19 | String name = Thread.currentThread().getName();
20 | System.out.println("当前线程名:" + name);
21 | System.out.println("main".equals(name));
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt03/FlagThreadExit.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt03;
2 |
3 | import java.util.concurrent.TimeUnit;
4 |
5 | /**
6 | * @author: mayuan
7 | * @desc:
8 | * @date: 2018/07/01
9 | */
10 | public class FlagThreadExit {
11 |
12 | public static void main(String[] args) throws InterruptedException {
13 | MyTask t = new MyTask();
14 | t.start();
15 |
16 | TimeUnit.SECONDS.sleep(5);
17 | System.out.println("System will be shutdown.");
18 | t.close();
19 | }
20 |
21 | static class MyTask extends Thread {
22 | private volatile boolean closed = false;
23 |
24 | @Override
25 | public void run() {
26 | System.out.println("I will start work.");
27 | while (!closed && !isInterrupted()) {
28 |
29 | }
30 | System.out.println("I will be exiting.");
31 | }
32 |
33 | public void close() {
34 | this.closed = true;
35 | this.interrupt();
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt03/ThreadInterrupt.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt03;
2 |
3 | import java.util.concurrent.TimeUnit;
4 |
5 | /**
6 | * @author: mayuan
7 | * @desc:
8 | * @date: 2018/06/30
9 | */
10 | public class ThreadInterrupt {
11 | public static void main(String[] args) throws InterruptedException {
12 | Thread thread = new Thread(() -> {
13 | try {
14 | TimeUnit.MINUTES.sleep(1);
15 | } catch (InterruptedException e) {
16 | System.out.println("Oh, i am be interrupted.");
17 | e.printStackTrace();
18 | }
19 | });
20 | thread.start();
21 |
22 | TimeUnit.MILLISECONDS.sleep(2);
23 | thread.interrupt();
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt03/ThreadInterrupted.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt03;
2 |
3 | import java.util.concurrent.TimeUnit;
4 |
5 | /**
6 | * @author: mayuan
7 | * @desc:
8 | * @date: 2018/06/30
9 | */
10 | public class ThreadInterrupted {
11 | public static void main(String[] args) throws InterruptedException {
12 | Thread thread = new Thread(() -> {
13 | while (true) {
14 |
15 | }
16 | });
17 | thread.start();
18 |
19 | TimeUnit.MILLISECONDS.sleep(2);
20 | System.out.printf("Thread is interrupted ? %s\n", thread.isInterrupted());
21 | thread.interrupt();
22 | System.out.printf("Thread is interrupted ? %s\n", thread.isInterrupted());
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt03/ThreadInterrupted2.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt03;
2 |
3 | import java.util.concurrent.TimeUnit;
4 |
5 | /**
6 | * @author: mayuan
7 | * @desc:
8 | * @date: 2018/06/30
9 | */
10 | public class ThreadInterrupted2 {
11 | public static void main(String[] args) throws InterruptedException {
12 | Thread thread = new Thread() {
13 | @Override
14 | public void run() {
15 | while (true) {
16 | try {
17 | TimeUnit.MINUTES.sleep(1);
18 | } catch (InterruptedException e) {
19 | System.out.printf("I am be interrupted ? %s\n", isInterrupted());
20 | }
21 | }
22 | }
23 | };
24 | thread.setDaemon(true);
25 | thread.start();
26 |
27 | TimeUnit.MILLISECONDS.sleep(2);
28 | System.out.printf("Thread be interrupted ? %s\n", thread.isInterrupted());
29 | Thread.interrupted();
30 | System.out.printf("Thread be interrupted ? %s\n", thread.isInterrupted());
31 | TimeUnit.MILLISECONDS.sleep(2);
32 | System.out.printf("Thread be interrupted ? %s\n", thread.isInterrupted());
33 |
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt03/ThreadInterrupted3.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt03;
2 |
3 | import java.util.concurrent.TimeUnit;
4 |
5 | /**
6 | * @author: mayuan
7 | * @desc:
8 | * @date: 2018/06/30
9 | */
10 | public class ThreadInterrupted3 {
11 | public static void main(String[] args) throws InterruptedException {
12 | Thread thread = new Thread() {
13 | @Override
14 | public void run() {
15 | while (true) {
16 | boolean fl = Thread.interrupted();
17 | if (fl){
18 | System.out.print("**************");
19 | }
20 | System.out.println(fl);
21 | }
22 | }
23 | };
24 | thread.setDaemon(true);
25 | thread.start();
26 |
27 | TimeUnit.MILLISECONDS.sleep(2);
28 | thread.interrupt();
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt03/ThreadInterrupted4.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt03;
2 |
3 | import java.util.concurrent.TimeUnit;
4 |
5 | /**
6 | * @author: mayuan
7 | * @desc:
8 | * @date: 2018/06/30
9 | */
10 | public class ThreadInterrupted4 {
11 | public static void main(String[] args) {
12 | System.out.println("Main thread is interrupted? " + Thread.interrupted());
13 |
14 | Thread.currentThread().interrupt();
15 |
16 | System.out.println("Main thread is interrupted? " + Thread.currentThread().isInterrupted());
17 |
18 | try {
19 | TimeUnit.MINUTES.sleep(1);
20 | } catch (InterruptedException e) {
21 | System.out.println("I will be interrupted still.");
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt03/ThreadPriority.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt03;
2 |
3 | import java.util.concurrent.TimeUnit;
4 |
5 | /**
6 | * @author: mayuan
7 | * @desc:
8 | * @date: 2018/06/30
9 | */
10 | public class ThreadPriority {
11 |
12 | public static void main(String[] args) {
13 | Thread t1 = new Thread(() -> {
14 | while (true) {
15 | System.out.println("t1");
16 | try {
17 | TimeUnit.SECONDS.sleep(2);
18 | } catch (InterruptedException e) {
19 | e.printStackTrace();
20 | }
21 | }
22 | });
23 | // 线程优先级最小为 1, 最大为 10, 默认为 5. 且不能大于线程所在 group 的优先级.
24 | t1.setPriority(3);
25 |
26 | Thread t2 = new Thread(() -> {
27 | while (true) {
28 | System.out.println("t2");
29 | try {
30 | TimeUnit.SECONDS.sleep(2);
31 | } catch (InterruptedException e) {
32 | e.printStackTrace();
33 | }
34 | }
35 | });
36 | t2.setPriority(10);
37 |
38 | t1.start();
39 | t2.start();
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt03/ThreadPriority2.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt03;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/06/30
7 | */
8 | public class ThreadPriority2 {
9 |
10 | public static void main(String[] args) {
11 | ThreadGroup group = new ThreadGroup("testGroup");
12 | // 将线程组的优先级指定为 7
13 | group.setMaxPriority(7);
14 | // 定义一个线程,将线程加入到 group 中
15 | Thread thread = new Thread(group, "test-thread");
16 | // 企图将线程的优先级设定为 10
17 | thread.setPriority(10);
18 | // 企图未遂
19 | System.out.println("线程真实优先级为: " + thread.getPriority());
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt03/ThreadPriority3.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt03;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/06/30
7 | */
8 | public class ThreadPriority3 {
9 | public static void main(String[] args) {
10 | Thread t1 = new Thread();
11 | System.out.println("t1 priority " + t1.getPriority());
12 |
13 | Thread t2 = new Thread(() -> {
14 | Thread t3 = new Thread();
15 | System.out.println("t3 priority " + t3.getPriority());
16 | });
17 |
18 | t2.setPriority(6);
19 | t2.start();
20 | System.out.println("t2 priority " + t2.getPriority());
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt03/ThreadSleep.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt03;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/06/29
7 | */
8 | public class ThreadSleep {
9 | public static void main(String[] args) {
10 | new Thread(() -> {
11 | long startTime = System.currentTimeMillis();
12 | sleep(2_000L);
13 | long endTime = System.currentTimeMillis();
14 | System.out.println(String.format("Current Thread Total spend %d ms", (endTime - startTime)));
15 | }).start();
16 |
17 | long startTime = System.currentTimeMillis();
18 | sleep(3_000L);
19 | long endTime = System.currentTimeMillis();
20 | System.out.println(String.format("Main Thread total spend %d ms", (endTime - startTime)));
21 |
22 | }
23 |
24 | private static void sleep(long ms) {
25 | try {
26 | if (ms < 0) {
27 | ms = 0;
28 | }
29 | Thread.sleep(ms);
30 | } catch (InterruptedException e) {
31 |
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt03/ThreadYield.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt03;
2 |
3 | import java.util.stream.IntStream;
4 |
5 | /**
6 | * @author: mayuan
7 | * @desc:
8 | * @date: 2018/06/29
9 | */
10 | public class ThreadYield {
11 |
12 | public static void main(String[] args) {
13 | IntStream.range(0, 2).mapToObj(ThreadYield::create).forEach(Thread::start);
14 | }
15 |
16 | private static Thread create(int index) {
17 | return new Thread(() -> {
18 | if (0 == index) {
19 | Thread.yield();
20 | }
21 | System.out.println(index);
22 | });
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt04/Mutex.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt04;
2 |
3 | import java.util.concurrent.TimeUnit;
4 |
5 | /**
6 | * @author: mayuan
7 | * @desc:
8 | * @date: 2018/07/01
9 | */
10 | public class Mutex {
11 | private final static Object MUTEX = new Object();
12 |
13 | public void accessResource() {
14 | synchronized (MUTEX) {
15 | try {
16 | TimeUnit.MINUTES.sleep(10);
17 | } catch (InterruptedException e) {
18 | e.printStackTrace();
19 | }
20 | }
21 | }
22 |
23 | public static void main(String[] args) {
24 | final Mutex mutex = new Mutex();
25 |
26 | for (int i = 0; i < 5; i++) {
27 | new Thread(mutex::accessResource).start();
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt04/ThisMonitor.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt04;
2 |
3 | import java.util.concurrent.TimeUnit;
4 |
5 | import static java.lang.Thread.currentThread;
6 |
7 | /**
8 | * @author: mayuan
9 | * @desc:
10 | * @date: 2018/07/02
11 | */
12 | public class ThisMonitor {
13 |
14 | public static void main(String[] args) {
15 | ThisMonitor thisMonitor = new ThisMonitor();
16 | new Thread(thisMonitor::method1, "T1").start();
17 | new Thread(thisMonitor::method2, "T2").start();
18 | }
19 |
20 | public synchronized void method1() {
21 | System.out.println(currentThread().getName() + " enter to method1.");
22 | try {
23 | TimeUnit.MINUTES.sleep(10);
24 | } catch (InterruptedException e) {
25 | e.printStackTrace();
26 | }
27 | }
28 |
29 | public synchronized void method2() {
30 | System.out.println(currentThread().getName() + " enter to method2.");
31 | try {
32 | TimeUnit.MINUTES.sleep(10);
33 | } catch (InterruptedException e) {
34 | e.printStackTrace();
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt04/ThisMonitor2.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt04;
2 |
3 | import java.util.concurrent.TimeUnit;
4 |
5 | import static java.lang.Thread.currentThread;
6 |
7 | /**
8 | * @author: mayuan
9 | * @desc:
10 | * @date: 2018/07/02
11 | */
12 | public class ThisMonitor2 {
13 |
14 | public static void main(String[] args) {
15 | ThisMonitor2 thisMonitor = new ThisMonitor2();
16 | new Thread(thisMonitor::method1, "T1").start();
17 | new Thread(thisMonitor::method2, "T2").start();
18 | }
19 |
20 | public synchronized void method1() {
21 | System.out.println(currentThread().getName() + " enter to method1.");
22 | try {
23 | TimeUnit.MINUTES.sleep(10);
24 | } catch (InterruptedException e) {
25 | e.printStackTrace();
26 | }
27 | }
28 |
29 | public void method2() {
30 | synchronized (this) {
31 | System.out.println(currentThread().getName() + " enter to method2.");
32 | try {
33 | TimeUnit.MINUTES.sleep(10);
34 | } catch (InterruptedException e) {
35 | e.printStackTrace();
36 | }
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt04/TicketWindowRunnable.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt04;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/01
7 | */
8 | public class TicketWindowRunnable implements Runnable {
9 | private int index = 1;
10 |
11 | private final static int MAX = 50;
12 |
13 | private final static Object MUTEX = new Object();
14 |
15 | @Override
16 | public void run() {
17 | synchronized (MUTEX) {
18 | while (index <= MAX) {
19 | System.out.println(Thread.currentThread() + " 的号码是:" + (index++));
20 | }
21 | }
22 | }
23 |
24 | public static void main(String[] args) {
25 | final TicketWindowRunnable task = new TicketWindowRunnable();
26 |
27 | Thread t1 = new Thread(task, "1号窗口");
28 |
29 | Thread t2 = new Thread(task, "2号窗口");
30 |
31 | Thread t3 = new Thread(task, "3号窗口");
32 |
33 | Thread t4 = new Thread(task, "4号窗口");
34 |
35 | t1.start();
36 | t2.start();
37 | t3.start();
38 | t4.start();
39 | }
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt05/EventClient.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt05;
2 |
3 | import java.util.concurrent.TimeUnit;
4 |
5 | /**
6 | * @author: mayuan
7 | * @desc:
8 | * @date: 2018/07/03
9 | */
10 | public class EventClient {
11 |
12 | public static void main(String[] args) {
13 | final EventQueue eventQueue = new EventQueue();
14 | new Thread(() -> {
15 | while (true) {
16 | eventQueue.offer(new EventQueue.Event());
17 | }
18 | }, "Producer").start();
19 |
20 | new Thread(() -> {
21 | while (true) {
22 | eventQueue.take();
23 | try {
24 | TimeUnit.SECONDS.sleep(10);
25 | } catch (InterruptedException e) {
26 | e.printStackTrace();
27 | }
28 | }
29 | }, "Consumer").start();
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt06/ThreadGroupCreateror.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt06;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/04
7 | */
8 | public class ThreadGroupCreateror {
9 | public static void main(String[] args) {
10 | ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
11 |
12 | ThreadGroup group1 = new ThreadGroup("Group1");
13 |
14 | System.out.println(currentGroup.getName());
15 | System.out.println(group1.getParent() == currentGroup);
16 |
17 | ThreadGroup group2 = new ThreadGroup("Group2");
18 |
19 | System.out.println(group1.getName());
20 | System.out.println(group2.getParent() == group1);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt07/CaptureThreadException.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt07;
2 |
3 | import java.util.concurrent.TimeUnit;
4 |
5 | /**
6 | * @author: mayuan
7 | * @desc:
8 | * @date: 2018/07/05
9 | */
10 | public class CaptureThreadException {
11 | public static void main(String[] args) {
12 | Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
13 | System.out.println(t.getName() + " occur exception.");
14 | e.printStackTrace();
15 | });
16 |
17 | final Thread thread = new Thread(() -> {
18 | try {
19 | TimeUnit.SECONDS.sleep(2);
20 | } catch (InterruptedException e) {
21 | }
22 |
23 | System.out.println(1 / 0);
24 | }, "Test-Thread");
25 |
26 | thread.start();
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt07/EmptyExceptionHandler.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt07;
2 |
3 | import java.util.concurrent.TimeUnit;
4 |
5 | /**
6 | * @author: mayuan
7 | * @desc:
8 | * @date: 2018/07/05
9 | */
10 | public class EmptyExceptionHandler {
11 |
12 | public static void main(String[] args) {
13 | ThreadGroup mainGroup = Thread.currentThread().getThreadGroup();
14 | System.out.println(mainGroup.getName());
15 | System.out.println(mainGroup.getParent());
16 | System.out.println(mainGroup.getParent().getParent());
17 |
18 | final Thread thread = new Thread(() -> {
19 | try {
20 | TimeUnit.SECONDS.sleep(2);
21 | } catch (InterruptedException e) {
22 | }
23 |
24 | System.out.println(1 / 0);
25 | }, "Test-Thread");
26 |
27 | thread.start();
28 |
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt09/ActiveLoadTest.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt09;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/07
7 | */
8 | public class ActiveLoadTest {
9 | public static void main(String[] args) {
10 | System.out.println(Child.y);
11 | // System.out.println(Child.x);
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt09/Child.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt09;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/07
7 | */
8 | public class Child extends Parent {
9 | static {
10 | System.out.println("The child will be initialized.");
11 | }
12 |
13 | public static int x = 10;
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt09/ClassInit.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt09;
2 |
3 | import java.util.concurrent.TimeUnit;
4 | import java.util.stream.IntStream;
5 |
6 | /**
7 | * @author: mayuan
8 | * @desc:
9 | * @date: 2018/07/07
10 | */
11 | public class ClassInit {
12 |
13 | static {
14 | try {
15 | System.out.println("The ClassInit static code block will be invoke.");
16 | TimeUnit.MINUTES.sleep(10);
17 | } catch (InterruptedException e) {
18 | e.printStackTrace();
19 | }
20 | }
21 |
22 | public static void main(String[] args) {
23 | IntStream.range(0, 5).forEach(i -> new Thread((ClassInit::new)));
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt09/Parent.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt09;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/07
7 | */
8 | public class Parent {
9 | static {
10 | System.out.println("The parent is initialized");
11 | }
12 |
13 | public static int y = 100;
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt09/Price.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt09;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/08
7 | */
8 | public class Price {
9 |
10 | final static Price instance = new Price(2.8);
11 |
12 | static double initPrice = 20;
13 |
14 | double currentPrice;
15 |
16 | public Price(double discount){
17 | currentPrice = initPrice - discount;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt09/PriceTest.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt09;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/08
7 | */
8 | public class PriceTest {
9 | public static void main(String[] args) {
10 | System.out.println(Price.instance.currentPrice);
11 | Price price = new Price(2.8);
12 | System.out.println(price.currentPrice);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt09/Singleton.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt09;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/07
7 | */
8 | public class Singleton {
9 |
10 | private static int x = 0;
11 |
12 | private static int y;
13 |
14 | private static Singleton instance = new Singleton();
15 |
16 | private Singleton() {
17 | x++;
18 | y++;
19 | }
20 |
21 | public static Singleton getInstance() {
22 | return instance;
23 | }
24 |
25 | public static void main(String[] args) {
26 | Singleton singleton = Singleton.getInstance();
27 | System.out.println(singleton.x);
28 | System.out.println(singleton.y);
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt09/Singleton2.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt09;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/07
7 | */
8 | public class Singleton2 {
9 |
10 | private static Singleton2 instance = new Singleton2();
11 |
12 | private static int x = 0;
13 |
14 | private static int y;
15 |
16 | private Singleton2() {
17 | x++;
18 | y++;
19 | }
20 |
21 | public static Singleton2 getInstance() {
22 | return instance;
23 | }
24 |
25 | public static void main(String[] args) {
26 | Singleton2 singleton = Singleton2.getInstance();
27 | System.out.println(singleton.x);
28 | System.out.println(singleton.y);
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt09/StaticInitTest.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt09;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/08
7 | */
8 | public class StaticInitTest {
9 |
10 | static int count = 2;
11 |
12 | static {
13 | System.out.println("StaticInitTest");
14 | name = "Java 编程";
15 | }
16 |
17 | static String name = "疯狂Java讲义";
18 |
19 | public static void main(String[] args) {
20 | System.out.println("count: " + count);
21 | System.out.println("name: " + name);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt10/ApplicationClassLoader.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt10;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/09
7 | */
8 | public class ApplicationClassLoader {
9 | public static void main(String[] args) {
10 | System.out.println(System.getProperty("java.class.path"));
11 | System.out.println(ApplicationClassLoader.class.getClassLoader());
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt10/BootstrapClassLoader.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt10;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/09
7 | */
8 | public class BootstrapClassLoader {
9 | public static void main(String[] args) {
10 | System.out.println("Bootstrap:" + String.class.getClassLoader());
11 | System.out.println(System.getProperty("sun.boot.class.path"));
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt10/ExtClassLoader.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt10;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/09
7 | */
8 | public class ExtClassLoader {
9 | public static void main(String[] args) {
10 | System.out.println(System.getProperty("java.ext.dirs"));
11 | System.out.println(ExtClassLoader.class.getClassLoader());
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/main/java/concurrent/cpt12/VolatileFoo.java:
--------------------------------------------------------------------------------
1 | package concurrent.cpt12;
2 |
3 | import java.util.concurrent.TimeUnit;
4 |
5 | /**
6 | * @author: mayuan
7 | * @desc:
8 | * @date: 2018/07/09
9 | */
10 | public class VolatileFoo {
11 |
12 | final static int MAX = 5;
13 | static int init_value = 0;
14 |
15 | public static void main(String[] args) {
16 | new Thread(() -> {
17 | int localValue = init_value;
18 | while (localValue < MAX) {
19 | if (localValue != init_value) {
20 | System.out.println("The init_value is updated to " + init_value);
21 | localValue = init_value;
22 | }
23 | }
24 | }, "Reader").start();
25 |
26 | new Thread(() -> {
27 | int localValue = init_value;
28 | while (localValue < MAX) {
29 | System.out.println("The init_value will be changed to " + (++localValue));
30 | init_value = localValue;
31 | try {
32 | TimeUnit.SECONDS.sleep(2);
33 | } catch (InterruptedException e) {
34 | e.printStackTrace();
35 | }
36 | }
37 | }, "Updater").start();
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/design/builder/Client.java:
--------------------------------------------------------------------------------
1 | package design.builder;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/14
7 | */
8 | public class Client {
9 | public static void main(String[] args) {
10 | MyStringBuilder msb = new MyStringBuilder();
11 | final int count = 26;
12 | for (int i = 0; i < count; i++) {
13 | msb.append((char) ('A' + i));
14 | }
15 | System.out.println(msb.toString());
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/design/builder/MyStringBuilder.java:
--------------------------------------------------------------------------------
1 | package design.builder;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/14
7 | */
8 | public class MyStringBuilder extends AbstractStringBuilder {
9 | public MyStringBuilder() {
10 | super(16);
11 | }
12 |
13 | @Override
14 | public String toString() {
15 | return new String(value, 0, count);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/design/chainofresponsibility/Client.java:
--------------------------------------------------------------------------------
1 | package design.chainofresponsibility;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/14
7 | */
8 | public class Client {
9 | public static void main(String[] args) {
10 | Handler handler1 = new ConcreteHandler1(null);
11 | Handler handler2 = new ConcreteHandler2(handler1);
12 |
13 | Request request1 = new Request(RequestType.type1, "request1");
14 | handler2.handleRequest(request1);
15 |
16 | Request request2 = new Request(RequestType.type2, "request2");
17 | handler2.handleRequest(request2);
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/design/chainofresponsibility/ConcreteHandler1.java:
--------------------------------------------------------------------------------
1 | package design.chainofresponsibility;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/14
7 | */
8 | public class ConcreteHandler1 extends Handler {
9 |
10 | public ConcreteHandler1(Handler successor) {
11 | super(successor);
12 | }
13 |
14 | @Override
15 | protected void handleRequest(Request request) {
16 | if (request.getType() == RequestType.type1) {
17 | System.out.println(request.getName() + " is handle by ConcreteHandler1");
18 | return;
19 | }
20 | if (null != successor) {
21 | successor.handleRequest(request);
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/design/chainofresponsibility/ConcreteHandler2.java:
--------------------------------------------------------------------------------
1 | package design.chainofresponsibility;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/14
7 | */
8 | public class ConcreteHandler2 extends Handler {
9 |
10 | public ConcreteHandler2(Handler successor) {
11 | super(successor);
12 | }
13 |
14 | @Override
15 | protected void handleRequest(Request request) {
16 | if (request.getType() == RequestType.type2) {
17 | System.out.println(request.getName() + " is handle by ConcreteHandler2");
18 | return;
19 | }
20 | if (null != successor) {
21 | successor.handleRequest(request);
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/design/chainofresponsibility/Handler.java:
--------------------------------------------------------------------------------
1 | package design.chainofresponsibility;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/14
7 | */
8 | public abstract class Handler {
9 | protected Handler successor;
10 |
11 | public Handler(Handler successor) {
12 | this.successor = successor;
13 | }
14 |
15 | protected abstract void handleRequest(Request request);
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/design/chainofresponsibility/Request.java:
--------------------------------------------------------------------------------
1 | package design.chainofresponsibility;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/14
7 | */
8 | public class Request {
9 | private RequestType type;
10 | private String name;
11 |
12 | public Request(RequestType type, String name) {
13 | this.type = type;
14 | this.name = name;
15 | }
16 |
17 | public RequestType getType() {
18 | return this.type;
19 | }
20 |
21 | public String getName() {
22 | return this.name;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/design/chainofresponsibility/RequestType.java:
--------------------------------------------------------------------------------
1 | package design.chainofresponsibility;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/14
7 | */
8 | public enum RequestType {
9 | /**
10 | * 类型1
11 | */
12 | type1,
13 | /**
14 | * 类型2
15 | */
16 | type2
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/design/command/Client.java:
--------------------------------------------------------------------------------
1 | package design.command;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/14
7 | */
8 | public class Client {
9 | public static void main(String[] args) {
10 | Invoker invoker = new Invoker();
11 | Light light = new Light();
12 |
13 | Command lightOnCommand = new LightOnCommand(light);
14 | Command lightOffCommand = new LightOffCommand(light);
15 |
16 | invoker.setOnCommand(lightOnCommand, 0);
17 | invoker.setOffCommand(lightOffCommand, 0);
18 |
19 | invoker.onButtonWasPushed(0);
20 | invoker.offButtonWasPushed(0);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/design/command/Command.java:
--------------------------------------------------------------------------------
1 | package design.command;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/14
7 | */
8 | public interface Command {
9 | void execute();
10 | }
11 |
--------------------------------------------------------------------------------
/src/main/java/design/command/Invoker.java:
--------------------------------------------------------------------------------
1 | package design.command;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/14
7 | */
8 | public class Invoker {
9 | private Command[] onCommands;
10 | private Command[] offCommands;
11 | private final int slotNum = 7;
12 |
13 | public Invoker() {
14 | this.onCommands = new Command[slotNum];
15 | this.offCommands = new Command[slotNum];
16 | }
17 |
18 | public void setOnCommand(Command command, int slot) {
19 | onCommands[slot] = command;
20 | }
21 |
22 | public void setOffCommand(Command command, int slot) {
23 | offCommands[slot] = command;
24 | }
25 |
26 | public void onButtonWasPushed(int slot) {
27 | onCommands[slot].execute();
28 | }
29 |
30 | public void offButtonWasPushed(int slot) {
31 | offCommands[slot].execute();
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/design/command/Light.java:
--------------------------------------------------------------------------------
1 | package design.command;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/14
7 | */
8 | public class Light {
9 | public void on() {
10 | System.out.println("Light is on!");
11 | }
12 |
13 | public void off() {
14 | System.out.println("Light is off!");
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/design/command/LightOffCommand.java:
--------------------------------------------------------------------------------
1 | package design.command;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/14
7 | */
8 | public class LightOffCommand implements Command {
9 | Light light;
10 |
11 | public LightOffCommand(Light light) {
12 | this.light = light;
13 | }
14 |
15 | @Override
16 | public void execute() {
17 | light.off();
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/design/command/LightOnCommand.java:
--------------------------------------------------------------------------------
1 | package design.command;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/14
7 | */
8 | public class LightOnCommand implements Command {
9 | Light light;
10 |
11 | public LightOnCommand(Light light) {
12 | this.light = light;
13 | }
14 |
15 | @Override
16 | public void execute() {
17 | light.on();
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/design/prototype/Client.java:
--------------------------------------------------------------------------------
1 | package design.prototype;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/14
7 | */
8 | public class Client {
9 | public static void main(String[] args) {
10 | Prototype prototype = new ConcretePrototype("abc");
11 | Prototype clone = prototype.myClone();
12 | System.out.println(clone);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/design/prototype/ConcretePrototype.java:
--------------------------------------------------------------------------------
1 | package design.prototype;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/14
7 | */
8 | public class ConcretePrototype extends Prototype {
9 |
10 | private String field;
11 |
12 | public ConcretePrototype(String f) {
13 | this.field = f;
14 | }
15 |
16 | @Override
17 | Prototype myClone() {
18 | return new ConcretePrototype(field);
19 | }
20 |
21 | @Override
22 | public String toString() {
23 | return field;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/design/prototype/Prototype.java:
--------------------------------------------------------------------------------
1 | package design.prototype;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/14
7 | */
8 | public abstract class Prototype {
9 | abstract Prototype myClone();
10 | }
11 |
--------------------------------------------------------------------------------
/src/main/java/design/simplefactory/Client.java:
--------------------------------------------------------------------------------
1 | package design.simplefactory;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/14
7 | */
8 | public class Client {
9 | public static void main(String[] args) {
10 | SimpleFactory simpleFactory = new SimpleFactory();
11 | Product product = simpleFactory.createProduct(1);
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/main/java/design/simplefactory/ConcreteProduct.java:
--------------------------------------------------------------------------------
1 | package design.simplefactory;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/14
7 | */
8 | public class ConcreteProduct implements Product{
9 | }
10 |
--------------------------------------------------------------------------------
/src/main/java/design/simplefactory/ConcreteProduct1.java:
--------------------------------------------------------------------------------
1 | package design.simplefactory;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/14
7 | */
8 | public class ConcreteProduct1 implements Product{
9 | }
10 |
--------------------------------------------------------------------------------
/src/main/java/design/simplefactory/ConcreteProduct2.java:
--------------------------------------------------------------------------------
1 | package design.simplefactory;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/14
7 | */
8 | public class ConcreteProduct2 implements Product{
9 | }
10 |
--------------------------------------------------------------------------------
/src/main/java/design/simplefactory/Product.java:
--------------------------------------------------------------------------------
1 | package design.simplefactory;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/14
7 | */
8 | public interface Product {
9 | }
10 |
--------------------------------------------------------------------------------
/src/main/java/design/simplefactory/SimpleFactory.java:
--------------------------------------------------------------------------------
1 | package design.simplefactory;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc:
6 | * @date: 2018/07/14
7 | */
8 | public class SimpleFactory {
9 | public Product createProduct(int type) {
10 | if (1 == type) {
11 | return new ConcreteProduct1();
12 | } else if (2 == type) {
13 | return new ConcreteProduct2();
14 | } else {
15 | return new ConcreteProduct();
16 | }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/design/singleton/Singleton01.java:
--------------------------------------------------------------------------------
1 | package design.singleton;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc: 懒汉式 - 线程不安全
6 | * @date: 2018/07/13
7 | */
8 | public class Singleton01 {
9 |
10 | private static Singleton01 uniqueInstance;
11 |
12 | private Singleton01() {
13 | }
14 |
15 | public static Singleton01 getUniqueInstance() {
16 | if (null == uniqueInstance) {
17 | uniqueInstance = new Singleton01();
18 | }
19 | return uniqueInstance;
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/design/singleton/Singleton02.java:
--------------------------------------------------------------------------------
1 | package design.singleton;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc: 懒汉式 - 线程安全
6 | * @date: 2018/07/13
7 | */
8 | public class Singleton02 {
9 | private static Singleton02 uniqueInstance;
10 |
11 | private Singleton02() {
12 | }
13 |
14 | public static synchronized Singleton02 getUniqueInstance() {
15 | if (null == uniqueInstance) {
16 | uniqueInstance = new Singleton02();
17 | }
18 | return uniqueInstance;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/design/singleton/Singleton03.java:
--------------------------------------------------------------------------------
1 | package design.singleton;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc: 饿汉式 - 线程安全
6 | * @date: 2018/07/13
7 | */
8 | public class Singleton03 {
9 | private static Singleton03 uniqueInstance = new Singleton03();
10 |
11 | private Singleton03() {
12 | }
13 |
14 | public static Singleton03 getUniqueInstance() {
15 | return uniqueInstance;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/design/singleton/Singleton04.java:
--------------------------------------------------------------------------------
1 | package design.singleton;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc: 双重校验锁 - 线程安全
6 | * @date: 2018/07/13
7 | */
8 | public class Singleton04 {
9 | private volatile static Singleton04 uniqueInstance;
10 |
11 | private Singleton04() {
12 | }
13 |
14 | public static Singleton04 getUniqueInstance() {
15 | if (null == uniqueInstance) {
16 | synchronized (Singleton04.class) {
17 | if (null == uniqueInstance) {
18 | uniqueInstance = new Singleton04();
19 | }
20 | }
21 | }
22 | return uniqueInstance;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/design/singleton/Singleton05.java:
--------------------------------------------------------------------------------
1 | package design.singleton;
2 |
3 | /**
4 | * @author: mayuan
5 | * @desc: 静态内部类实现
6 | * @date: 2018/07/13
7 | */
8 | public class Singleton05 {
9 |
10 | private Singleton05() {
11 | }
12 |
13 | private static class SingletonHolder {
14 | private static final Singleton05 INSTANCE = new Singleton05();
15 | }
16 |
17 | public static Singleton05 getUniqueInstance() {
18 | return SingletonHolder.INSTANCE;
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------