├── LICENSE
├── README.md
├── pom.xml
└── thread-examples
├── sequenceDiagram.txt
└── src
└── me
└── edagarli
├── Main.java
├── Util
├── CastUtil.java
└── RandomUtil.java
├── alg
├── MoneyCalControMain.java
├── MoneyCalMain.java
└── array
│ ├── BinarySearch.java
│ ├── LengthMinSubArray.java
│ ├── RemoveYuanshu.java
│ └── SortArrayPingfang.java
├── annotations
├── TestAnnotations.java
└── Test_Target.java
├── code
└── KeyGen.java
├── disruptor
├── DisruptorTest.java
├── IntEvent.java
├── IntEventExceptionHandler.java
├── IntEventProcessor.java
└── IntEventProducer.java
├── heap
└── HeapAlloc.java
├── jvm
└── PermOOM.java
├── netty
├── ByteBufferTest.java
├── EchoServerHandler.java
├── TimeServer.java
└── TimeServerHandler.java
├── pro
├── CodeTest.java
└── StreamTest.java
├── project
├── AutoTest.java
├── ETagQUes.java
├── ForeachTest.java
├── JsoupCookieTest.java
└── Peopl.java
├── qlexpress
└── ExpressTest.java
├── thread
├── AtomicTest.java
├── Counter.java
├── DNSResolver.java
├── DNSTest.java
├── DnsResolverWithTimeout.java
├── SemaphoreTest.java
├── TestFreeList.java
└── ThreadPoolTest.java
└── uml
└── TestFlow.java
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2016 lizhi
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # JavaDayAndDay
2 | A self-taught project to learn Java.
3 |
4 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | me.edagarli
8 | JavaDayAndDay
9 | 1.0-SNAPSHOT
10 |
11 |
12 |
13 | com.aliyun.openservices
14 | ons-client
15 | 1.1.8
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 | com.alibaba.toolkit
25 | toolkit-common-convert
26 | 1.0
27 |
28 |
29 | org.jsoup
30 | jsoup
31 | 1.7.2
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 | org.apache.commons
40 | commons-lang3
41 | 3.2.1
42 |
43 |
44 | commons-collections
45 | commons-collections
46 | 3.2.2
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 | com.alibaba.toolkit
56 | toolkit-common-convert
57 | 1.0
58 |
59 |
60 |
61 |
62 | thread-examples/src
63 |
64 |
65 | org.apache.maven.plugins
66 | maven-compiler-plugin
67 |
68 |
69 | compile
70 | compile
71 |
72 | compile
73 |
74 |
75 |
76 | testCompile
77 | test-compile
78 |
79 | testCompile
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
--------------------------------------------------------------------------------
/thread-examples/sequenceDiagram.txt:
--------------------------------------------------------------------------------
1 | @startuml
2 | Alice -> Bob: test
3 | @enduml
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/Main.java:
--------------------------------------------------------------------------------
1 | package me.edagarli;
2 |
3 |
4 | /**
5 | * User: edagarli
6 | * Email: lizhi@edagarli.com
7 | * Desc:
8 | */
9 |
10 | public class Main {
11 |
12 | public static void main(String[] args) {
13 |
14 | // List list = new ArrayList();
15 | // list.add(new Date(1459844531000L));
16 | // list.add(new Date(1459844511000L));
17 | // Collections.sort(list , new Comparator() {
18 | // @Override
19 | // public int compare(Date o1, Date o2) {
20 | // return o1.compareTo(o2);
21 | // }
22 | // });
23 | //
24 | // for(Date d : list){
25 | // System.out.println(d);
26 | // }
27 |
28 | StringBuilder builder = new StringBuilder();
29 | try {
30 | System.out.println(Thread.currentThread());
31 | System.out.println(1 / 0);
32 | } catch (Exception e) {
33 | // e.printStackTrace();
34 | System.out.println(e);
35 | System.out.println(e.toString());
36 | System.out.println("--------------------");
37 | System.out.println(e.getMessage());
38 | System.out.println("--------------------");
39 | System.out.println(e.getStackTrace());
40 | System.out.println("--------------------");
41 | System.out.println(e.getCause());
42 | System.out.println("--------------------");
43 | //String fullStackTrace = ExceptionUtil.getStackTrace(e);
44 | //System.out.println(fullStackTrace);
45 | // System.out.println(e.fillInStackTrace());
46 | // StackTraceElement[] st = Thread.currentThread().getStackTrace();
47 | // for (StackTraceElement item : st) {
48 | // builder.append(item.getFileName()).append(":").append(item.getLineNumber());
49 | // builder.append(item.getClassName()).append(":").append(item.getMethodName()).append(System.lineSeparator());
50 | // }
51 | // System.out.println(exceptionToStr(e));
52 | StringBuffer sbf = new StringBuffer(e.getClass().getName()+": "+e.getMessage()+"\n");
53 | System.out.println(Thread.currentThread());
54 | StackTraceElement[] ste = Thread.currentThread().getStackTrace();
55 | for(int i=0;i createBonusList(Integer totalBonus, Integer totalNum, Integer authorNum) {
62 | Integer sendedBonus = 0;
63 | Integer sendedNum = 0;
64 | Integer rdMin = (int) (totalBonus / totalNum * 0.5);
65 | Integer rdMax = (int) (totalBonus / totalNum * 2);
66 | rdMax = Math.min(rdMax, authorNum);
67 | List bonusList = new ArrayList<>();
68 | while (sendedNum < totalNum) {
69 | Integer bonus = randomBonusWithSpecifyBound(totalBonus, totalNum, sendedBonus, sendedNum, rdMin, rdMax);
70 | bonusList.add(Convert.asDouble(bonus) / 100);
71 | sendedNum++;
72 | sendedBonus += bonus;
73 | }
74 | return bonusList;
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/alg/MoneyCalMain.java:
--------------------------------------------------------------------------------
1 | package me.edagarli.alg;
2 |
3 | import java.math.BigDecimal;
4 | import java.util.ArrayList;
5 | import java.util.List;
6 | import java.util.Random;
7 |
8 | /**
9 | * @author: edagarli(卤肉)
10 | * Email: lizhi@edagarli.com
11 | * github: http://github.com/edagarli
12 | * Date: 2018/11/12
13 | * Time: 23:54
14 | * Desc:
15 | */
16 | public class MoneyCalMain {
17 |
18 | public static void main(String[] args) throws Exception {
19 | // try {
20 | // //6个人
21 | // int cnt = 6;
22 | // //金额78块
23 | // BigDecimal all = new BigDecimal("78");
24 | // //团长金额
25 | // BigDecimal tuan = new BigDecimal("2200");
26 | // all = all.multiply(new BigDecimal(100));
27 | // for (int i = 0; i < 100; i++)
28 | // {
29 | // getRandom(cnt, all, tuan);
30 | // }
31 | // } catch (Exception e) {
32 | // e.printStackTrace();
33 | // }
34 | for (int i=0; i<10; i++) {
35 | System.out.println(getRandomList(5, 3));
36 | }
37 | }
38 |
39 | private static List getRandomList(int n, long seed) {
40 | Random random = new Random(seed);
41 | List randomList = new ArrayList<>();
42 | for (int i = 0; i < n; i++) {
43 | randomList.add(random.nextFloat());
44 | }
45 | return randomList;
46 | }
47 |
48 | private static void getRandom(int cnt, BigDecimal all, BigDecimal tu) throws Exception {
49 | List list = new ArrayList<>();
50 | int res = 0;
51 | int min = all.intValue() / cnt ;
52 | for (int i = 0; i < cnt; i++) {
53 | int max = ((all.intValue() - res) / cnt * 2) > tu.intValue() ? tu.intValue() : ((all.intValue() - res) / cnt * 2);
54 | int rand = 0;
55 | if (cnt - i == 1) {
56 | rand = all.intValue() - res;
57 | }
58 | else {
59 | rand = randInt(min, max);
60 | // rand = new Random().nextInt(max) + 1;
61 | }
62 | BigDecimal result = new BigDecimal(rand).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_DOWN);
63 | list.add(result);
64 | res += rand;
65 | }
66 | System.out.println(list);
67 | }
68 |
69 | private static int randInt(int min, int max) {
70 | Random rand = new Random();
71 | int randomNum;
72 | // if(max <= min) {
73 | // randomNum = rand.nextInt((min - max) + 1) + max;
74 | // } else {
75 | randomNum = rand.nextInt((max - min) + 1) + min;
76 | // }
77 | return randomNum;
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/alg/array/BinarySearch.java:
--------------------------------------------------------------------------------
1 | /**
2 | * alibaba.com Inc.
3 | * Copyright (c) 2004-2020 All Rights Reserved.
4 | */
5 | package me.edagarli.alg.array;
6 |
7 | /**
8 | * @author edagarli.lz
9 | * @version 1.0.0
10 | * @ClassName BinarySearch.java
11 | * @description
12 | *
13 | *
14 | *二分搜索
15 | *
16 | * 输入: nums = [-1,0,3,5,9,12], target = 2
17 | * 输出: -1
18 | * 解释: 2 不存在 nums 中因此返回 -1
19 | *
20 | * 你可以假设 nums 中的所有元素是不重复的。
21 | * n 将在 [1, 10000]之间。
22 | * nums 的每个元素都将在 [-9999, 9999]之间。
23 | * 时间复杂度:O(log n)
24 | * 空间复杂度:O(1)
25 | * #
26 | *
27 | * @createTime 2023年06月17日 17:55
28 | */
29 | public class BinarySearch {
30 |
31 | public int search(int[] nums, int target) {
32 |
33 | if (target < nums[0] || target > nums[nums.length - 1]) {
34 | return -1;
35 | }
36 |
37 | int left = 0, right = nums.length - 1;
38 | while (left <= right) {
39 | int mid = left + ((right - left) >> 1);
40 | if (nums[mid] == target) {
41 | return mid;
42 | } else if (nums[mid] < target) {
43 | left = mid + 1;
44 | } else if (nums[mid] > target) {
45 | right = mid - 1;
46 | }
47 | }
48 |
49 | return -1;
50 | }
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/alg/array/LengthMinSubArray.java:
--------------------------------------------------------------------------------
1 | /**
2 | * alibaba.com Inc.
3 | * Copyright (c) 2004-2020 All Rights Reserved.
4 | */
5 | package me.edagarli.alg.array;
6 |
7 | import java.util.HashMap;
8 | import java.util.Map;
9 |
10 | /**
11 | * @author edagarli.lz
12 | * @version 1.0.0
13 | * @ClassName LengthMinSubArray.java
14 | * @description
15 | *
16 | * 时间复杂度:O(n)
17 | * 空间复杂度:O(1)
18 | * 一些录友会疑惑为什么时间复杂度是O(n)。
19 | *
20 | * 不要以为for里放一个while就以为是O(n^2)啊, 主要是看每一个元素被操作的次数,每个元素在滑动窗后进来操作一次,出去操作一次,每个元素都是被操作两次,所以时间复杂度是 2 × n 也就是O(n)。
21 | *
22 | * 复杂度分析
23 | *
24 | * 时间复杂度:
25 | * �
26 | * (
27 | * �
28 | * )
29 | * O(n),其中
30 | * �
31 | * n 是数组
32 | * fruits
33 | * fruits 的长度。
34 | *
35 | * 空间复杂度:
36 | * �
37 | * (
38 | * 1
39 | * )
40 | * O(1)。哈希表中最多会有三个键值对,可以看成使用了常数级别的空间。
41 | *
42 | * 作者:LeetCode-Solution
43 | * 链接:https://leetcode.cn/problems/fruit-into-baskets/solution/shui-guo-cheng-lan-by-leetcode-solution-1uyu/
44 | * 来源:力扣(LeetCode)
45 | * 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
46 | *
47 | * @createTime 2023年06月20日 21:53
48 | */
49 | public class LengthMinSubArray {
50 |
51 |
52 | // 滑动窗口
53 | public int minSubArrayLen(int s, int[] nums) {
54 |
55 |
56 | int left = 0;
57 | int sum = 0;
58 | int result = Integer.MAX_VALUE;
59 | for (int right = 0; right < nums.length; right++) {
60 |
61 | sum += nums[right];
62 |
63 | while (sum >= s) {
64 |
65 |
66 | result = Math.min(result, right - left + 1);
67 |
68 | sum -= nums[left++];
69 |
70 |
71 | }
72 |
73 | }
74 |
75 | return result == Integer.MAX_VALUE ? 0 : result;
76 | }
77 |
78 |
79 | public static int totalFruit(int[] fruits) {
80 |
81 | int n = fruits.length;
82 | Map cnt = new HashMap();
83 |
84 | int left = 0, ans = 0;
85 | for (int right = 0; right < n; right++) {
86 | cnt.put(fruits[right], cnt.getOrDefault(fruits[right], 0) + 1);
87 | while (cnt.size() > 2) {
88 | cnt.put(fruits[left], cnt.get(fruits[left]) - 1);
89 | if (cnt.get(fruits[left]) == 0) {
90 | cnt.remove(fruits[left]);
91 | }
92 | ++left;
93 | }
94 | ans = Math.max(ans, right - left + 1);
95 | }
96 | return ans;
97 | }
98 |
99 |
100 | public static void main(String[] args) {
101 |
102 | //int[] fruits = {3,3,3,1,2,1,1,2,3,3,4};
103 | //System.out.println(totalFruit(fruits));
104 |
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/alg/array/RemoveYuanshu.java:
--------------------------------------------------------------------------------
1 | /**
2 | * alibaba.com Inc.
3 | * Copyright (c) 2004-2020 All Rights Reserved.
4 | */
5 | package me.edagarli.alg.array;
6 |
7 | /**
8 | * @author edagarli.lz
9 | * @version 1.0.0
10 | * @ClassName RemoveYuanshu.java
11 | * @description
12 | *
13 | * 双指针法(快慢指针法)
14 | *
15 | *示例 1: 给定 nums = [3,2,2,3], val = 3, 函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。 你不需要考虑数组中超出新长度后面的元素。
16 | *
17 | * 示例 2: 给定 nums = [0,1,2,2,3,0,4,2], val = 2, 函数应该返回新的长度 5, 并且 nums 中的前五个元素为 0, 1, 3, 0, 4。
18 | *
19 | * 你不需要考虑数组中超出新长度后面的元素。
20 | * 时间复杂度:O(n)
21 | * 空间复杂度:O(1)
22 | *
23 | *
24 | * @createTime 2023年06月18日 19:16
25 | */
26 | public class RemoveYuanshu {
27 |
28 | public int removeElement(int[] nums, int val) {
29 | // 快慢指针
30 | int slowIndex = 0;
31 | for (int fastIndex =0; fastIndex < nums.length; fastIndex++) {
32 | if (nums[fastIndex] != val) {
33 | nums[slowIndex] = nums[fastIndex];
34 | slowIndex++;
35 | }
36 | }
37 | return slowIndex;
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/alg/array/SortArrayPingfang.java:
--------------------------------------------------------------------------------
1 | /**
2 | * alibaba.com Inc.
3 | * Copyright (c) 2004-2020 All Rights Reserved.
4 | */
5 | package me.edagarli.alg.array;
6 |
7 | /**
8 | * @author edagarli.lz
9 | * @version 1.0.0
10 | * @ClassName SortArrayPingfang.java
11 | * @description 有序数组的平方
12 | *
13 | *
14 | * @createTime 2023年06月18日 20:13
15 | */
16 | public class SortArrayPingfang {
17 |
18 |
19 | public static int[] sortedSquares(int[] nums) {
20 |
21 | int right = nums.length - 1;
22 | int left = 0;
23 |
24 | int[] result = new int[nums.length];
25 |
26 | int index = result.length - 1;
27 |
28 | while (left <= right) {
29 |
30 | if (nums[left] * nums[left] > nums[right] * nums[right]) {
31 |
32 | result[index--] = nums[left] * nums[left] ;
33 | ++left;
34 |
35 | } else {
36 |
37 | result[index--] = nums[right] * nums[right];
38 | --right;
39 |
40 | }
41 |
42 | }
43 |
44 | return result;
45 | }
46 |
47 | public static void main(String[] args) {
48 |
49 | int[] nums = {-4,-1,0,3,10};
50 |
51 | System.out.println(sortedSquares(nums));
52 |
53 | }
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/annotations/TestAnnotations.java:
--------------------------------------------------------------------------------
1 | package me.edagarli.annotations;
2 |
3 | public class TestAnnotations {
4 | public static void main(String arg[]) {
5 | new TestAnnotations().doTestTargets();
6 | }
7 | // 在方法上使用注解,OK.
8 | // 中间也可以不换行,换2行之类,Java忽略多余的换行
9 | @Test_Target(doTestTarget="Hello World !")
10 | public void doTestTargets() {
11 | // System.out.printf("Testing Target annotation");
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/annotations/Test_Target.java:
--------------------------------------------------------------------------------
1 | package me.edagarli.annotations;
2 |
3 | import java.lang.annotation.ElementType;
4 | import java.lang.annotation.Target;
5 |
6 | @Target(ElementType.METHOD)
7 | public @interface Test_Target {
8 | public String doTestTarget();
9 | }
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/code/KeyGen.java:
--------------------------------------------------------------------------------
1 | package me.edagarli.code;
2 | import java.math.BigInteger;
3 | import java.util.Date;
4 | import java.util.Random;
5 | import java.util.Scanner;
6 | import java.util.zip.CRC32;
7 | public class KeyGen {
8 | public static short getCRC(String s, int i, byte bytes[]){
9 | CRC32 crc32 = new CRC32();
10 | if (s != null)
11 | {
12 | for (int j = 0; j < s.length(); j++)
13 | {
14 | char c = s.charAt(j);
15 | crc32.update(c);
16 | }
17 | }
18 | crc32.update(i);
19 | crc32.update(i >> 8);
20 | crc32.update(i >> 16);
21 | crc32.update(i >> 24);
22 | for (int k = 0; k < bytes.length - 2; k++)
23 | {
24 | byte byte0 = bytes[k];
25 | crc32.update(byte0);
26 | }
27 | return (short) (int) crc32.getValue();
28 | }
29 |
30 | public static String encodeGroups(BigInteger biginteger){
31 | BigInteger beginner1 = BigInteger.valueOf(0x39aa400L);
32 | StringBuilder sb = new StringBuilder();
33 | for (int i = 0; biginteger.compareTo(BigInteger.ZERO) != 0; i++)
34 | {
35 | int j = biginteger.mod(beginner1).intValue();
36 | String s1 = encodeGroup(j);
37 | if (i > 0)
38 | {
39 | sb.append("-");
40 | }
41 | sb.append(s1);
42 | biginteger = biginteger.divide(beginner1);
43 | }
44 | return sb.toString();
45 | }
46 |
47 | public static String encodeGroup(int i){
48 | StringBuilder sb = new StringBuilder();
49 | for (int j = 0; j < 5; j++)
50 | {
51 | int k = i % 36;
52 | char c;
53 | if (k < 10)
54 | {
55 | c = (char) (48 + k);
56 | }
57 | else
58 | {
59 | c = (char) ((65 + k) - 10);
60 | }
61 | sb.append(c);
62 | i /= 36;
63 | }
64 | return sb.toString();
65 | }
66 |
67 | public static String MakeKey(String name, int days, int id){
68 | id %= 100000;
69 | byte bkey[] = new byte[12];
70 | bkey[0] = (byte) 1; // Product type: IntelliJ IDEA is 1
71 | bkey[1] = 14; // version
72 | Date d = new Date();
73 | long ld = (d.getTime() >> 16);
74 | bkey[2] = (byte) (ld & 255);
75 | bkey[3] = (byte) ((ld >> 8) & 255);
76 | bkey[4] = (byte) ((ld >> 16) & 255);
77 | bkey[5] = (byte) ((ld >> 24) & 255);
78 | days &= 0xffff;
79 | bkey[6] = (byte) (days & 255);
80 | bkey[7] = (byte) ((days >> 8) & 255);
81 | bkey[8] = 105;
82 | bkey[9] = -59;
83 | bkey[10] = 0;
84 | bkey[11] = 0;
85 | int w = getCRC(name, id % 100000, bkey);
86 | bkey[10] = (byte) (w & 255);
87 | bkey[11] = (byte) ((w >> 8) & 255);
88 | BigInteger pow = new BigInteger("89126272330128007543578052027888001981", 10);
89 | BigInteger mod = new BigInteger("86f71688cdd2612ca117d1f54bdae029", 16);
90 | BigInteger k0 = new BigInteger(bkey);
91 | BigInteger k1 = k0.modPow(pow, mod);
92 | String s0 = Integer.toString(id);
93 | String sz = "0";
94 | while (s0.length() != 5)
95 | {
96 | s0 = sz.concat(s0);
97 | }
98 | s0 = s0.concat("-");
99 | String s1 = encodeGroups(k1);
100 | s0 = s0.concat(s1);
101 | return s0;
102 | }
103 |
104 | public static void main(String[] args){
105 | System.out.println("请输入用户名:");
106 | Scanner scanner = new Scanner(System.in);
107 | String username = scanner.next();
108 | Random r = new Random();
109 | System.out.println(MakeKey(username, 0, r.nextInt(100000)));
110 | }
111 | }
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/disruptor/DisruptorTest.java:
--------------------------------------------------------------------------------
1 | //package me.edagarli.disruptor;
2 | //
3 | //import com.lmax.disruptor.*;
4 | //
5 | //import java.util.ArrayList;
6 | //import java.util.List;
7 | //import java.util.concurrent.LinkedBlockingQueue;
8 | //import java.util.concurrent.ThreadPoolExecutor;
9 | //import java.util.concurrent.TimeUnit;
10 | //
11 | ///**
12 | // * User: edagarli
13 | // * Email: lizhi@edagarli.com
14 | // * Date: 16/5/21
15 | // * Time: 15:08
16 | // * Desc:
17 | // */
18 | //public class DisruptorTest {
19 | // public static void main(String[] args) throws InterruptedException {
20 | // //创建一个RingBuffer对象
21 | // RingBuffer ringBuffer = new RingBuffer(IntEvent.INT_ENEVT_FACTORY,
22 | // new SingleThreadedClaimStrategy(16), new SleepingWaitStrategy());
23 | // SequenceBarrier sequenceBarrier = ringBuffer.newBarrier();
24 | // IntEventProducer[] producers = new IntEventProducer[1];
25 | // for(int i=0; i < producers.length; i++){
26 | // producers[i] = new IntEventProducer();
27 | // }
28 | // WorkerPool crawler = new WorkerPool(ringBuffer, sequenceBarrier, new IntEventExceptionHandler(), producers);
29 | // SequenceBarrier sb = ringBuffer.newBarrier(crawler.getWorkerSequences());
30 | // IntEventProcessor[] processors = new IntEventProcessor[1];
31 | // for (int i = 0; i applier = new WorkerPool(ringBuffer, sb, new IntEventExceptionHandler(), processors);
35 | // List gatingSequences = new ArrayList();
36 | // for(Sequence s : crawler.getWorkerSequences()) {
37 | // gatingSequences.add(s);
38 | // }
39 | // for(Sequence s : applier.getWorkerSequences()) {
40 | // gatingSequences.add(s);
41 | // }
42 | // ringBuffer.setGatingSequences(gatingSequences.toArray(new Sequence[gatingSequences.size()]));
43 | // ThreadPoolExecutor executor = new ThreadPoolExecutor(7, 7, 10, TimeUnit.MINUTES,new LinkedBlockingQueue(5));
44 | // crawler.start(executor);
45 | // applier.start(executor);
46 | // while (true) {
47 | // Thread.sleep(1000);
48 | // long lastSeq = ringBuffer.next();
49 | // ringBuffer.publish(lastSeq);
50 | // }
51 | // }
52 | //}
53 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/disruptor/IntEvent.java:
--------------------------------------------------------------------------------
1 | //package me.edagarli.disruptor;
2 | //
3 | //import com.lmax.disruptor.EventFactory;
4 | //
5 | ///**
6 | // * User: edagarli
7 | // * Email: lizhi@edagarli.com
8 | // * Date: 16/5/21
9 | // * Time: 14:56
10 | // * Desc: RingBuffer中存储的单元
11 | // */
12 | //public class IntEvent {
13 | // private int value = -1;
14 | //
15 | // public int getValue() {
16 | // return value;
17 | // }
18 | //
19 | // public void setValue(int value) {
20 | // this.value = value;
21 | // }
22 | //
23 | // @Override
24 | // public String toString() {
25 | // return String.valueOf(value);
26 | // }
27 | //
28 | // public static EventFactory INT_ENEVT_FACTORY = new EventFactory() {
29 | // public IntEvent newInstance() {
30 | // return new IntEvent();
31 | // }
32 | // };
33 | //}
34 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/disruptor/IntEventExceptionHandler.java:
--------------------------------------------------------------------------------
1 | //package me.edagarli.disruptor;
2 | //
3 | //import com.lmax.disruptor.ExceptionHandler;
4 | //
5 | ///**
6 | // * User: edagarli
7 | // * Email: lizhi@edagarli.com
8 | // * Date: 16/5/21
9 | // * Time: 15:21
10 | // * Desc:
11 | // */
12 | //public class IntEventExceptionHandler implements ExceptionHandler {
13 | // public void handleEventException(Throwable throwable, long l, Object o) {
14 | // }
15 | //
16 | // public void handleOnStartException(Throwable throwable) {
17 | // }
18 | //
19 | // public void handleOnShutdownException(Throwable throwable) {
20 | // }
21 | //}
22 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/disruptor/IntEventProcessor.java:
--------------------------------------------------------------------------------
1 | //package me.edagarli.disruptor;
2 | //
3 | ////import com.lmax.disruptor.WorkHandler;
4 | //
5 | ///**
6 | // * User: edagarli
7 | // * Email: lizhi@edagarli.com
8 | // * Date: 16/5/21
9 | // * Time: 15:07
10 | // * Desc:
11 | // */
12 | //public class IntEventProcessor implements WorkHandler {
13 | // public void onEvent(IntEvent event) throws Exception {
14 | // System.out.println(event.getValue());
15 | // event.setValue(1);
16 | // }
17 | //}
18 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/disruptor/IntEventProducer.java:
--------------------------------------------------------------------------------
1 | //package me.edagarli.disruptor;
2 | //
3 | //import com.lmax.disruptor.WorkHandler;
4 | //
5 | ///**
6 | // * User: edagarli
7 | // * Email: lizhi@edagarli.com
8 | // * Date: 16/5/21
9 | // * Time: 15:05
10 | // * Desc:
11 | // */
12 | //public class IntEventProducer implements WorkHandler {
13 | // private int seq = 0;
14 | //
15 | // @Override
16 | // public void onEvent(IntEvent intEvent) throws Exception {
17 | // System.out.println("produced " + seq);
18 | // intEvent.setValue(++seq);
19 | // }
20 | //}
21 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/heap/HeapAlloc.java:
--------------------------------------------------------------------------------
1 | package me.edagarli.heap;
2 |
3 | /**
4 | * User: edagarli
5 | * Email: lizhi@edagarli.com
6 | * Date: 16/4/14
7 | * Time: 00:05
8 | * Desc:
9 | */
10 | public class HeapAlloc {
11 | public static void main(String[] args){
12 | System.out.println("maxMemory=");
13 | System.out.println(Runtime.getRuntime().maxMemory() / 1024 /1024+" M");
14 | System.out.println("free mem=");
15 | System.out.println(Runtime.getRuntime().freeMemory() / 1024 /1024+" M");
16 | System.out.println("total mem=");
17 | System.out.println(Runtime.getRuntime().totalMemory() / 1024 /1024+" M");
18 |
19 | byte[] b = new byte[1*1024*1024];
20 | System.out.println("分配了1M空间给数组");
21 |
22 | System.out.println("maxMemory=");
23 | System.out.println(Runtime.getRuntime().maxMemory() / 1024 /1024+" M");
24 | System.out.println("free mem=");
25 | System.out.println(Runtime.getRuntime().freeMemory() / 1024 /1024+" M");
26 | System.out.println("total mem=");
27 | System.out.println(Runtime.getRuntime().totalMemory() / 1024 /1024+" M");
28 |
29 | b = new byte[4*1024*1024];
30 | System.out.println("分配了4M空间给数组");
31 |
32 | System.out.println("maxMemory=");
33 | System.out.println(Runtime.getRuntime().maxMemory() / 1024 /1024+" M");
34 | System.out.println("free mem=");
35 | System.out.println(Runtime.getRuntime().freeMemory() / 1024 /1024+" M");
36 | System.out.println("total mem=");
37 | System.out.println(Runtime.getRuntime().totalMemory() / 1024 /1024+" M");
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/jvm/PermOOM.java:
--------------------------------------------------------------------------------
1 | package me.edagarli.jvm;
2 |
3 | /**
4 | * User: edagarli(卤肉)
5 | * Email: lizhi@edagarli.com
6 | * github: http://github.com/edagarli
7 | * Date: 16/12/28
8 | * Time: 23:44
9 | * Desc:
10 | */
11 | public class PermOOM {
12 |
13 | public static void main(String args[]){
14 | try{
15 | for (int i = 0; i < 100000; i++) {
16 | // -XX:MaxPermSize = 5m
17 | }
18 | }catch (Exception e){
19 |
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/netty/ByteBufferTest.java:
--------------------------------------------------------------------------------
1 | package me.edagarli.netty;
2 |
3 | import io.netty.buffer.ByteBuf;
4 | import io.netty.buffer.Unpooled;
5 |
6 | /**
7 | * User: edagarli(卤肉)
8 | * Email: lizhi@edagarli.com
9 | * github: http://github.com/edagarli
10 | * Date: 16/11/11
11 | * Time: 22:07
12 | * Desc:
13 | */
14 | public class ByteBufferTest {
15 |
16 | public static void main(String args[]) {
17 |
18 | // String content = "hello,world";
19 | // ByteBuffer byteBuffer = ByteBuffer.allocate(256);
20 | // byteBuffer.put(content.getBytes());
21 | // byteBuffer.flip();
22 | // byte[] bufferValue = new byte[byteBuffer.remaining()];
23 | // System.out.println(byteBuffer.get(bufferValue));
24 | // System.out.println(new String(bufferValue));
25 | ByteBuf byteBuf = Unpooled.buffer(16);
26 | ByteBuf byteBuf2 = Unpooled.buffer(8);
27 | byteBuf.writeInt(1);
28 | byteBuf.writeInt(2);
29 | byteBuf.writeInt(3);
30 | System.out.println("读之后writerIndex:" + byteBuf.writerIndex());
31 | System.out.println("读之后readerIndex:" + byteBuf.readerIndex());
32 | System.out.println("读之后2的可读长度:" + byteBuf.readableBytes());
33 | System.out.println("读之后2的可写长度:" + byteBuf.writableBytes());
34 |
35 | System.out.println("读之后writerIndex:" + byteBuf2.writerIndex());
36 | System.out.println("读之后readerIndex:" + byteBuf2.readerIndex());
37 | System.out.println("读之后2的可读长度:" + byteBuf2.readableBytes());
38 | System.out.println("读之后2的可写长度:" + byteBuf2.writableBytes());
39 |
40 | System.out.println(byteBuf);
41 | System.out.println(byteBuf2);
42 |
43 | // byteBuf2.writeInt(1);
44 | // byteBuf2.writeBytes(byteBuf);
45 | byteBuf.readBytes(byteBuf2);
46 |
47 | System.out.println(byteBuf);
48 | System.out.println(byteBuf2);
49 |
50 | System.out.println("读之后writerIndex:" + byteBuf.writerIndex());
51 | System.out.println("读之后readerIndex:" + byteBuf.readerIndex());
52 | System.out.println("读之后2的可读长度:" + byteBuf.readableBytes());
53 | System.out.println("读之后2的可写长度:" + byteBuf.writableBytes());
54 |
55 | System.out.println("读之后writerIndex:" + byteBuf2.writerIndex());
56 | System.out.println("读之后readerIndex:" + byteBuf2.readerIndex());
57 | System.out.println("读之后2的可读长度:" + byteBuf2.readableBytes());
58 | System.out.println("读之后2的可写长度:" + byteBuf2.writableBytes());
59 | }
60 |
61 | }
62 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/netty/EchoServerHandler.java:
--------------------------------------------------------------------------------
1 | package me.edagarli.netty;
2 |
3 |
4 | import io.netty.buffer.ByteBuf;
5 | import io.netty.buffer.Unpooled;
6 | import io.netty.channel.*;
7 | import io.netty.channel.ChannelHandler.Sharable;
8 |
9 | @Sharable
10 | public class EchoServerHandler extends ChannelInboundHandlerAdapter {
11 |
12 | @Override
13 | public void channelActive(ChannelHandlerContext ctx) throws Exception {
14 | ChannelPipeline cp = ctx.pipeline();
15 | cp.write(1);
16 | cp.write(2);
17 | cp.write(3);
18 | cp.write(4).addListener(new ChannelFutureListener() {
19 |
20 | public void operationComplete(ChannelFuture future)
21 | throws Exception {
22 | future.channel().pipeline().close();
23 | }
24 | });
25 | }
26 |
27 | /**
28 | * byteBuf.hasArray 如果为true,此byteBuf为堆内存字节缓冲区,换句话说,在jvm的堆内存上
29 | * 如果为false,此byteBuf为直接内存字节缓冲区,放在内存里。
30 | * 区别:堆内存缓冲区对处理socket数据稍差,因为实际上socket会把数据从堆内存拷贝到机器的内存中再发送,处理遗留数据好用
31 | * 直接内存缓冲区不需要复制,但是控制此byteBuf的生命周期不是很容易,也不容易处理遗留数据,需要把遗留数据拷贝到堆内存中
32 | */
33 | @Override
34 | public void channelRead(ChannelHandlerContext ctx, Object msg)
35 | throws Exception {
36 | ByteBuf bb = (ByteBuf) msg;
37 | // System.out.println(bb.toString(CharsetUtil.UTF_8));
38 | // if (!bb.hasArray()) {
39 | // byte[] array = new byte[bb.readableBytes()];
40 | // System.out.println("getBytes前,可读长度:" + bb.readableBytes());
41 | // bb.getBytes(bb.readerIndex(), array);
42 | // System.out.println("getBytes后,可读长度:" + bb.readableBytes());
43 | // }
44 | // ByteBuf newB = Unpooled.EMPTY_BUFFER;
45 | // CompositeByteBuf compositeB = Unpooled.compositeBuffer();
46 | // compositeB.addComponents(newB, bb);
47 | //
48 | // // 从compositeByteBuf中读取数据跟从直接内存缓冲区中读取数据一致
49 | // byte[] tempBuffer = new byte[compositeB.readableBytes()];
50 | // compositeB.getBytes(compositeB.readerIndex(), tempBuffer);
51 |
52 | ByteBuf testRW1 = Unpooled.buffer(16, 16);
53 | ByteBuf testRW2 = Unpooled.buffer(16, 16);
54 |
55 | testRW1.writeInt(1);
56 | testRW1.writeInt(2);
57 | testRW1.writeInt(3);
58 |
59 | testRW2.writeInt(4);
60 | testRW2.writeInt(5);
61 |
62 | System.out.println("读之前可读长度:" + testRW1.readableBytes());
63 | System.out.println("读之前可写长度:" + testRW1.writableBytes());
64 |
65 | System.out.println("读之前writerIndex:" + testRW1.writerIndex());
66 | System.out.println("读之前readerIndex:" + testRW1.readerIndex());
67 |
68 | System.out.println("2的readIndex" + testRW2.readerIndex());
69 | System.out.println("2的writIndex" + testRW2.writerIndex());
70 |
71 | System.out.println("2的可读" + testRW2.readableBytes());
72 | System.out.println("2的可写" + testRW2.writableBytes());
73 |
74 | // while (testRW1.isReadable()) {
75 | testRW1.readBytes(testRW2);
76 | System.out.println(testRW1.readableBytes());
77 | // }
78 |
79 | System.out.println("读之后可读长度:" + testRW1.readableBytes());
80 | System.out.println("读之后可写长度:" + testRW1.writableBytes());
81 |
82 | System.out.println("读之后writerIndex:" + testRW1.writerIndex());
83 | System.out.println("读之后readerIndex:" + testRW1.readerIndex());
84 |
85 | System.out.println("读之后2的可读长度:" + testRW2.readableBytes());
86 | System.out.println("读之后2的可写长度:" + testRW2.writableBytes());
87 |
88 | System.out.println(testRW2.readerIndex());
89 | System.out.println(testRW2.writerIndex());
90 |
91 | ctx.write(bb);
92 | }
93 |
94 | @Override
95 | public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
96 | ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(
97 | ChannelFutureListener.CLOSE);
98 | }
99 |
100 | @Override
101 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
102 | throws Exception {
103 | ctx.writeAndFlush("error server".getBytes());
104 | cause.printStackTrace();
105 | ctx.close();
106 | }
107 |
108 | }
109 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/netty/TimeServer.java:
--------------------------------------------------------------------------------
1 | package me.edagarli.netty;
2 |
3 | import io.netty.bootstrap.ServerBootstrap;
4 | import io.netty.channel.ChannelFuture;
5 | import io.netty.channel.ChannelInitializer;
6 | import io.netty.channel.ChannelOption;
7 | import io.netty.channel.EventLoopGroup;
8 | import io.netty.channel.nio.NioEventLoopGroup;
9 | import io.netty.channel.socket.SocketChannel;
10 | import io.netty.channel.socket.nio.NioServerSocketChannel;
11 |
12 | /**
13 | * User: edagarli
14 | * Email: lizhi@edagarli.com
15 | * Date: 16/5/24
16 | * Time: 17:42
17 | * Desc:
18 | */
19 | public class TimeServer {
20 |
21 | public void bind(int port) throws Exception {
22 | EventLoopGroup bossGroup = new NioEventLoopGroup();
23 | EventLoopGroup workerGroup = new NioEventLoopGroup();
24 | try{
25 | ServerBootstrap b = new ServerBootstrap();
26 | b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
27 | .option(ChannelOption.SO_BACKLOG, 1024)
28 | .childHandler(new ChildChannelHandler());
29 | ChannelFuture f = b.bind(port).sync();
30 |
31 | f.channel().closeFuture().sync();
32 | }finally {
33 | bossGroup.shutdownGracefully();
34 | workerGroup.shutdownGracefully();
35 | }
36 | }
37 |
38 | private class ChildChannelHandler extends ChannelInitializer {
39 | protected void initChannel(SocketChannel socketChannel) throws Exception {
40 | socketChannel.pipeline().addLast(new TimeServerHandler());
41 | }
42 | }
43 |
44 | public static void main(String[] args) throws Exception {
45 | int port = 8080;
46 | if(args != null && args.length > 0){
47 | try{
48 | port = Integer.valueOf(args[0]);
49 | } catch(NumberFormatException e){
50 |
51 | }
52 | }
53 | new TimeServer().bind(port);
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/netty/TimeServerHandler.java:
--------------------------------------------------------------------------------
1 | package me.edagarli.netty;
2 |
3 | import io.netty.channel.ChannelHandlerAdapter;
4 | import io.netty.channel.ChannelHandlerContext;
5 |
6 | /**
7 | * User: edagarli
8 | * Email: lizhi@edagarli.com
9 | * Date: 16/5/24
10 | * Time: 18:02
11 | * Desc:
12 | */
13 | public class TimeServerHandler extends ChannelHandlerAdapter {
14 |
15 | @Override
16 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
17 | super.exceptionCaught(ctx, cause);
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/pro/CodeTest.java:
--------------------------------------------------------------------------------
1 | package me.edagarli.pro;
2 |
3 | /**
4 | * User: edagarli
5 | * Email: lizhi@edagarli.com
6 | * Date: 16/6/7
7 | * Time: 15:22
8 | * Desc:
9 | */
10 | public class CodeTest {
11 |
12 | public static final String FORMAT_ZW_URL = "%sma/order/%s/%s/%s";
13 |
14 | public static void main(String args[]){
15 | String longUrl = String.format(FORMAT_ZW_URL, new Object[]{"http://blog.edagarli.com/", "99001331", "B2", "klfkafjaoidhqdihqiodhqj"});
16 | System.out.println(longUrl);
17 | String string = "wddksj";
18 | String[] parts = string.split("-");
19 | String part1 = parts[0];
20 | // String part2 = parts[1];
21 | System.out.println(part1 +"===>");
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/pro/StreamTest.java:
--------------------------------------------------------------------------------
1 | package me.edagarli.pro;
2 |
3 | import com.alibaba.common.convert.Convert;
4 | import com.alibaba.fastjson.JSONArray;
5 | import com.alibaba.fastjson.JSONObject;
6 | import org.apache.commons.collections.CollectionUtils;
7 |
8 | import java.util.ArrayList;
9 | import java.util.List;
10 | import java.util.stream.Collectors;
11 |
12 | public class StreamTest {
13 |
14 | public static void main(String args[]) {
15 |
16 | String json = "[\n" +
17 | " \"{\\\"appCatName\\\":\\\"market\\\",\\\"appName\\\":\\\"test\\\",\\\"entityId\\\":\\\"99930982\\\",\\\"instanceId\\\":\\\"313067d122e5444ab7bb33d51e89a7dd\\\",\\\"internalType\\\":1}\",\n" +
18 | " \"{\\\"appCatName\\\":\\\"market\\\",\\\"appName\\\":\\\"test\\\",\\\"entityId\\\":\\\"99930982\\\",\\\"instanceId\\\":\\\"b2c89004abf54520b3aa0a68db06f797\\\",\\\"internalType\\\":1}\",\n" +
19 | " \"{\\\"appCatName\\\":\\\"market\\\",\\\"appName\\\":\\\"test\\\",\\\"entityId\\\":\\\"99930982\\\",\\\"instanceId\\\":\\\"3c7a98db4c8c4cc9956dea4dd8099467\\\",\\\"internalType\\\":1}\",\n" +
20 | " \"{\\\"appCatName\\\":\\\"market\\\",\\\"appName\\\":\\\"test\\\",\\\"entityId\\\":\\\"99930982\\\",\\\"instanceId\\\":\\\"17510771c4154271a47a6d9f26d6fbcf\\\",\\\"internalType\\\":1}\",\n" +
21 | " \"{\\\"appCatName\\\":\\\"market\\\",\\\"appName\\\":\\\"test\\\",\\\"entityId\\\":\\\"99930982\\\",\\\"instanceId\\\":\\\"b32e4267cadc4033b4cd3b441f9408a7\\\",\\\"internalType\\\":1}\"\n" +
22 | "]";
23 | JSONArray jsonArray = JSONArray.parseArray(json);
24 | if (CollectionUtils.isEmpty(jsonArray)) {
25 | return ;
26 | }
27 | jsonArray.stream().map((obj) -> {
28 | JSONObject jsonObject = JSONObject.parseObject(Convert.asString(obj));
29 | if (null == jsonObject || null == jsonObject.get("internalType")) {
30 | return true;
31 | }
32 | if (Convert.asByte(jsonObject.get("internalType"))
33 | == Convert.asByte(1)) {
34 | System.out.println(1);
35 | return true;
36 | }
37 | return true;
38 | }).collect(Collectors.toList());
39 |
40 | List list = new ArrayList();
41 | list.add(1);
42 | list.add(2);
43 | list.add(3);
44 | // list.stream().map((e) -> {
45 | // System.out.println(e);
46 | // return e;
47 | // }).collect(Collectors.toList());
48 | list.stream().forEach(integer -> System.out.println(integer));
49 | }
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/project/AutoTest.java:
--------------------------------------------------------------------------------
1 | package me.edagarli.project;
2 |
3 | /**
4 | * User: edagarli
5 | * Email: lizhi@edagarli.com
6 | * github: http://github.com/edagarli
7 | * Date: 16/10/17
8 | * Time: 13:58
9 | * Desc:
10 | */
11 | public class AutoTest {
12 | public static void main(String[] agrs){
13 | String string=null;
14 | if(!"ccc".equals(string)) {
15 | System.out.println("---------");
16 | }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/project/ETagQUes.java:
--------------------------------------------------------------------------------
1 | package me.edagarli.project;
2 |
3 |
4 | import org.apache.commons.lang3.StringUtils;
5 |
6 | /**
7 | * User: edagarli(卤肉)
8 | * Email: lizhi@edagarli.com
9 | * github: http://github.com/edagarli
10 | * Date: 16/11/10
11 | * Time: 15:15
12 | * Desc:
13 | */
14 | public class ETagQUes {
15 |
16 | public static void main(String args[]){
17 | StringBuffer eTag = new StringBuffer(StringUtils.EMPTY);
18 | sss(eTag);
19 | System.out.println(eTag);
20 | System.out.println(eTag.toString());
21 | System.out.println(eTag.toString().hashCode());
22 | System.out.println(String.valueOf(eTag.toString().hashCode()));
23 | }
24 |
25 | public static String sss(StringBuffer eTag){
26 | eTag.append("Sdsf");
27 | return null;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/project/ForeachTest.java:
--------------------------------------------------------------------------------
1 | package me.edagarli.project;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Map;
6 | import java.util.TreeMap;
7 |
8 | /**
9 | * User: edagarli
10 | * Email: lizhi@edagarli.com
11 | * github: http://github.com/edagarli
12 | * Date: 16/8/8
13 | * Time: 12:47
14 | * Desc:
15 | */
16 | public class ForeachTest {
17 | public static void main(String[] args) {
18 | Map> map = new TreeMap>();
19 | test(map);
20 | List newClient = map.get("1");
21 | for(Peopl peopl : newClient){
22 | System.out.println("llllll"+peopl.getName());
23 | }
24 | }
25 |
26 | public static void test(Map> map){
27 | for(int i=0;i<9;i++){
28 | List client = new ArrayList();
29 | map.put(String.valueOf(i), client);
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/project/JsoupCookieTest.java:
--------------------------------------------------------------------------------
1 | package me.edagarli.project;
2 |
3 | import org.jsoup.Connection;
4 | import org.jsoup.Jsoup;
5 |
6 | import javax.net.ssl.HostnameVerifier;
7 | import javax.net.ssl.HttpsURLConnection;
8 | import javax.net.ssl.SSLSession;
9 | import java.io.IOException;
10 |
11 | /**
12 | * User: edagarli
13 | * Email: lizhi@edagarli.com
14 | * github: http://github.com/edagarli
15 | * Date: 16/9/26
16 | * Time: 11:05
17 | * Desc:
18 | */
19 | public class JsoupCookieTest {
20 |
21 | public static HostnameVerifier hv = new HostnameVerifier() {
22 | public boolean verify(String urlHostName, SSLSession session) {
23 | System.out.println("Warning: URL Host: " + urlHostName + " vs. "
24 | + session.getPeerHost());
25 | return true;
26 | }
27 | };
28 |
29 | public static void main(String[] args) throws Exception {
30 | trustAllHttpsCertificates();
31 | HttpsURLConnection.setDefaultHostnameVerifier(hv);
32 | Connection conn = Jsoup.connect("https://2dfire.com/");
33 | conn.method(Connection.Method.GET);
34 | conn.followRedirects(false);
35 | Connection.Response response = conn.execute();
36 | System.out.println(response.cookies());
37 | System.out.println(response.cookies().get("token"));
38 | }
39 |
40 |
41 | private static void trustAllHttpsCertificates() throws Exception {
42 | javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
43 | javax.net.ssl.TrustManager tm = new miTM();
44 | trustAllCerts[0] = tm;
45 | javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext
46 | .getInstance("SSL");
47 | sc.init(null, trustAllCerts, null);
48 | javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc
49 | .getSocketFactory());
50 | }
51 |
52 | static class miTM implements javax.net.ssl.TrustManager,
53 | javax.net.ssl.X509TrustManager {
54 | public java.security.cert.X509Certificate[] getAcceptedIssuers() {
55 | return null;
56 | }
57 |
58 | public boolean isServerTrusted(
59 | java.security.cert.X509Certificate[] certs) {
60 | return true;
61 | }
62 |
63 | public boolean isClientTrusted(
64 | java.security.cert.X509Certificate[] certs) {
65 | return true;
66 | }
67 |
68 | public void checkServerTrusted(
69 | java.security.cert.X509Certificate[] certs, String authType)
70 | throws java.security.cert.CertificateException {
71 | return;
72 | }
73 |
74 | public void checkClientTrusted(
75 | java.security.cert.X509Certificate[] certs, String authType)
76 | throws java.security.cert.CertificateException {
77 | return;
78 | }
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/project/Peopl.java:
--------------------------------------------------------------------------------
1 | package me.edagarli.project;
2 |
3 | import java.io.Serializable;
4 |
5 | /**
6 | * User: edagarli
7 | * Email: lizhi@edagarli.com
8 | * github: http://github.com/edagarli
9 | * Date: 16/8/8
10 | * Time: 12:49
11 | * Desc:
12 | */
13 | public class Peopl implements Serializable{
14 |
15 | private String name ;
16 |
17 | public String getName() {
18 | return name;
19 | }
20 |
21 | public void setName(String name) {
22 | this.name = name;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/qlexpress/ExpressTest.java:
--------------------------------------------------------------------------------
1 | //package me.edagarli.qlexpress;
2 | //
3 | //import com.ql.util.express.DefaultContext;
4 | //import com.ql.util.express.ExpressRunner;
5 | //
6 | ///**
7 | // * User: edagarli(卤肉)
8 | // * Email: lizhi@edagarli.com
9 | // * github: http://github.com/edagarli
10 | // * Date: 2017/7/20
11 | // * Time: 20:29
12 | // * Desc:
13 | // */
14 | //public class ExpressTest {
15 | //
16 | // public static void main (String args[]) {
17 | // try {
18 | // ExpressRunner runner = new ExpressRunner();
19 | // DefaultContext context = new DefaultContext();
20 | // context.put("a",1);
21 | // context.put("b",2);
22 | // context.put("c",3);
23 | // String express = "a+b*c";
24 | // Object r = runner.execute(express, context, null, true, false);
25 | // System.out.println(r);
26 | // } catch (Exception e) {
27 | // e.printStackTrace();
28 | // }
29 | // }
30 | //
31 | //}
32 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/thread/AtomicTest.java:
--------------------------------------------------------------------------------
1 | package me.edagarli.thread;
2 |
3 | import java.util.concurrent.atomic.AtomicInteger;
4 |
5 | /**
6 | * User: edagarli
7 | * Email: lizhi@edagarli.com
8 | * Date: 16/5/17
9 | * Time: 20:30
10 | * Desc:
11 | */
12 | public class AtomicTest {
13 | private final static AtomicInteger threadNumber = new AtomicInteger(1);
14 |
15 | public static void main(String[] args) {
16 | for(int i = 0; i < 10000; i++){
17 | new Thread(new Runnable() {
18 | public void run() {
19 | if(threadNumber.get() > 1){
20 | System.out.println(Thread.currentThread().getName()+" value="+threadNumber.get()+" return null");
21 | }else{
22 | threadNumber.incrementAndGet();
23 | try {
24 | Thread.sleep(10000);
25 | } catch (InterruptedException e) {
26 | e.printStackTrace();
27 | }
28 | System.out.println(Thread.currentThread().getName()+" value="+threadNumber.get()+" ok!");
29 | threadNumber.decrementAndGet();
30 | }
31 | System.out.println("threadNumber::"+threadNumber.get());
32 | }
33 | }).start();
34 | try {
35 | Thread.sleep(1000);
36 | } catch (InterruptedException e) {
37 | e.printStackTrace();
38 | }
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/thread/Counter.java:
--------------------------------------------------------------------------------
1 | package me.edagarli.thread;
2 |
3 | import java.util.concurrent.CountDownLatch;
4 | import java.util.concurrent.atomic.AtomicInteger;
5 |
6 | /**
7 | * User: edagarli
8 | * Email: lizhi@edagarli.com
9 | * Date: 16/5/18
10 | * Time: 10:51
11 | * Desc:
12 | */
13 | public class Counter {
14 | public static AtomicInteger count = new AtomicInteger(0);
15 |
16 | public static void inc() {
17 |
18 | //这里延迟1毫秒,使得结果明显
19 | try {
20 | Thread.sleep(1);
21 | } catch (InterruptedException e) {
22 | }
23 | count.getAndIncrement();
24 | }
25 |
26 | public static void main(String[] args) throws InterruptedException {
27 |
28 | final CountDownLatch latch = new CountDownLatch(1000);
29 | //同时启动1000个线程,去进行i++计算,看看实际结果
30 | for (int i = 0; i < 1000; i++) {
31 | new Thread(new Runnable() {
32 | @Override
33 | public void run() {
34 | Counter.inc();
35 | latch.countDown();
36 | }
37 | }).start();
38 | }
39 | latch.await();
40 | //这里每次运行的值都有可能不同,可能为1000
41 | System.out.println("运行结果:Counter.count=" + Counter.count);
42 | }
43 | }
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/thread/DNSResolver.java:
--------------------------------------------------------------------------------
1 | package me.edagarli.thread;
2 |
3 | import java.net.InetAddress;
4 | import java.net.UnknownHostException;
5 |
6 | /**
7 | * User: edagarli
8 | * Email: lizhi@edagarli.com
9 | * Date: 16/5/28
10 | * Time: 15:57
11 | * Desc:
12 | */
13 | public class DNSResolver implements Runnable {
14 | private String domain;
15 | private InetAddress inetAddr;
16 |
17 | public DNSResolver(String domain) {
18 | this.domain = domain;
19 | }
20 |
21 | public void run() {
22 | try {
23 | InetAddress addr = InetAddress.getByName(domain);
24 | set(addr);
25 | } catch (UnknownHostException e) {
26 |
27 | }
28 | }
29 |
30 | public synchronized void set(InetAddress inetAddr) {
31 | this.inetAddr = inetAddr;
32 | }
33 | public synchronized InetAddress get() {
34 | return inetAddr;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/thread/DNSTest.java:
--------------------------------------------------------------------------------
1 | package me.edagarli.thread;
2 |
3 | import java.net.InetAddress;
4 | import java.net.UnknownHostException;
5 |
6 | /**
7 | * User: edagarli
8 | * Email: lizhi@edagarli.com
9 | * Date: 16/5/28
10 | * Time: 15:41
11 | * Desc:
12 | */
13 | public class DNSTest {
14 | private static final String host = "localhost";
15 | public static void main(String args[]){
16 | DNSResolver dnsRes = new DNSResolver(host);
17 | Thread t = new Thread(dnsRes);
18 | t.start();
19 | try {
20 | t.join(1000);
21 | InetAddress inetAddr = dnsRes.get();
22 | System.out.println(inetAddr);
23 | } catch (InterruptedException e) {
24 | e.printStackTrace();
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/thread/DnsResolverWithTimeout.java:
--------------------------------------------------------------------------------
1 | package me.edagarli.thread;
2 |
3 |
4 | /**
5 | * User: edagarli
6 | * Email: lizhi@edagarli.com
7 | * Date: 16/5/28
8 | * Time: 15:54
9 | * Desc:
10 | */
11 | public class DnsResolverWithTimeout{
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/thread/SemaphoreTest.java:
--------------------------------------------------------------------------------
1 | package me.edagarli.thread;
2 |
3 | import java.util.concurrent.ExecutorService;
4 | import java.util.concurrent.Executors;
5 | import java.util.concurrent.Semaphore;
6 |
7 | /**
8 | * User: edagarli
9 | * Email: lizhi@edagarli.com
10 | * Date: 16/5/17
11 | * Time: 11:56
12 | * Desc:
13 | */
14 | public class SemaphoreTest {
15 |
16 | private static final int THREAD_COUNT = 30;
17 |
18 | private static ExecutorService threadPool = Executors
19 | .newFixedThreadPool(THREAD_COUNT);
20 |
21 | private static Semaphore s = new Semaphore(10);
22 |
23 | public static void main(String[] args) {
24 | for (int i = 0; i < THREAD_COUNT; i++) {
25 | threadPool.execute(new Runnable() {
26 | @Override
27 | public void run() {
28 | try {
29 | System.out.printf("%s: Going to print a job\n", Thread.currentThread().getName());
30 | s.acquire();
31 | Thread.sleep((long) (Math.random() * 6000));
32 | s.release();
33 | System.out.printf("%s: The document has been printed\n", Thread.currentThread().getName());
34 | } catch (InterruptedException e) {
35 | e.printStackTrace();
36 | }
37 | }
38 | });
39 | }
40 |
41 | threadPool.shutdown();
42 | }
43 | }
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/thread/TestFreeList.java:
--------------------------------------------------------------------------------
1 | package me.edagarli.thread;
2 |
3 | import java.util.*;
4 | import java.util.concurrent.BlockingQueue;
5 | import java.util.concurrent.LinkedBlockingDeque;
6 | import java.util.concurrent.ThreadPoolExecutor;
7 | import java.util.concurrent.TimeUnit;
8 | import java.util.concurrent.atomic.AtomicInteger;
9 |
10 | /**
11 | * User: edagarli
12 | * Email: lizhi@edagarli.com
13 | * Date: 16/4/16
14 | * Time: 15:30
15 | * Desc: test LockFreeList, LockFreeVector, Vector, LinkedList
16 | */
17 | public class TestFreeList {
18 |
19 | private static final int MAX_THREADS = 2000;
20 |
21 | private static final int TASK_COUNT = 4000;
22 |
23 | List list;
24 |
25 | public class AccessListThread implements Runnable {
26 | protected String name;
27 | java.util.Random random = new java.util.Random();
28 | public AccessListThread(){
29 |
30 | }
31 | public AccessListThread(String name){
32 | this.name = name;
33 | }
34 |
35 | @Override
36 | public void run() {
37 | try{
38 | for(int i=0; i<1000; i++)
39 | handleList(random.nextInt(1000));
40 | Thread.sleep(random.nextInt(100));
41 | } catch (InterruptedException e){
42 | e.printStackTrace();
43 | }
44 | }
45 | }
46 |
47 | public class CounterPoolExecutor extends ThreadPoolExecutor{
48 | private AtomicInteger count = new AtomicInteger(0);
49 | public long startTime = 0;
50 | public String funcName = "";
51 |
52 | public CounterPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue) {
53 | super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
54 | }
55 |
56 | @Override
57 | protected void afterExecute(Runnable r, Throwable t) {
58 | int l = count.addAndGet(1);
59 | if(l == TASK_COUNT){
60 | System.out.println(funcName + " spend time:" + (System.currentTimeMillis() - startTime));
61 | }
62 | }
63 | }
64 |
65 | public Object handleList(int index){
66 | list.add(index);
67 | list.remove(index % list.size());
68 | return null;
69 | }
70 |
71 | public void initLinkedList(){
72 | List l = new ArrayList();
73 | for(int i=0; i<1000; i++){
74 | l.add(i);
75 | }
76 | list = Collections.synchronizedList(new LinkedList(l));
77 | }
78 |
79 | public void initVector(){
80 | List l = new ArrayList();
81 | for (int i=0; i<1000; i++)
82 | l.add(i);
83 | list = new Vector(l);
84 | }
85 |
86 | public void initFreeLockList(){
87 | List l = new ArrayList();
88 | for(int i=0; i<1000; i++)
89 | l.add(i);
90 | // list = new org.amino.ds.lockfree.LockFreeList(l);
91 | }
92 |
93 | public void initFreeLockVector(){
94 | // list = new org.amino.ds.lockfree.LockFreeVector();
95 | for(int i=0; i<1000; i++){
96 | list.add(i);
97 | }
98 | }
99 |
100 | public void testFreeLockList() throws InterruptedException {
101 | initFreeLockList();
102 | CounterPoolExecutor exe = new CounterPoolExecutor(MAX_THREADS,MAX_THREADS,0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque());
103 | long startTime = System.currentTimeMillis();
104 | exe.startTime = startTime;
105 | exe.funcName = "testFreeLockList";
106 | Runnable t = new AccessListThread();
107 | for (int i=0; i());
116 | long startTime = System.currentTimeMillis();
117 | exe.startTime = startTime;
118 | exe.funcName = "testFreeLockList";
119 | Runnable t = new AccessListThread();
120 | for (int i=0; i());
129 | long startTime = System.currentTimeMillis();
130 | exe.startTime = startTime;
131 | exe.funcName = "testFreeLockList";
132 | Runnable t = new AccessListThread();
133 | for (int i=0; i());
142 | long startTime = System.currentTimeMillis();
143 | exe.startTime = startTime;
144 | exe.funcName = "testFreeLockList";
145 | Runnable t = new AccessListThread();
146 | for (int i=0; i= 3 ) {
46 | try {
47 | this.wait();
48 | } catch (InterruptedException e) {
49 | e.printStackTrace();
50 | }
51 | }
52 |
53 | // Only serves 100 people one day.
54 | if (count > 100) {
55 | this.holes.shutdown();
56 | return false;
57 | } else {
58 | this.peopleIn(((People)people).name);
59 | holes.submit(people);
60 | return true;
61 | }
62 | }
63 |
64 | private synchronized void enEn(String name, int v) {
65 | this.volume += v;
66 | System.out.println("People["+name+"] put in ["+v+"]. Toilet volume increases to ["+volume+"]");
67 |
68 | // If the volume exceeds capacity, notify cleaner to clean.
69 | if (this.volume > this.CAPACITY) {
70 | this.notifyCleaner();
71 | }
72 | }
73 |
74 | private void notifyCleaner() {
75 | if (this.cleaning == false) {
76 | System.out.println("Toilet volume full with ["+volume+"]. Notify cleaner.");
77 | holes.submit(cleaner);
78 | }
79 | }
80 |
81 | private synchronized void peopleIn(String name) {
82 | System.out.println("People["+name+"] comes in.");
83 | this.peopleIn ++;
84 | this.count++;
85 | }
86 |
87 | private synchronized void peopleOut(String name) {
88 | System.out.println("People["+name+"] comes out.");
89 | this.peopleIn --;
90 | this.notifyAll();
91 | }
92 | public synchronized void cleaning() {
93 | this.cleaning = true;
94 |
95 | }
96 | public synchronized void cleaned() {
97 | this.cleaning = false;
98 | this.notifyAll();
99 | }
100 | }
101 |
102 | // One toilet cleaner.
103 | private class Cleaner implements Runnable {
104 | private Toilet toilet;
105 | private Cleaner(Toilet t) {
106 | this.toilet = t;
107 | }
108 |
109 | @Override
110 | public void run() {
111 | toilet.cleaning();
112 | System.out.println("Toilet Cleaning...");
113 | try {
114 | Thread.sleep(2000);
115 | } catch (InterruptedException e) {
116 | e.printStackTrace();
117 | }
118 | this.toilet.volume = 0;
119 | System.out.println("Toilet Clean done.");
120 | toilet.cleaning = false;
121 | toilet.cleaned();
122 | }
123 | }
124 |
125 | private class People implements Runnable {
126 | private Toilet toilet;
127 | private String name;
128 | private People(String name, Toilet t) {
129 | this.toilet = t;
130 | this.name = name;
131 | }
132 |
133 | @Override
134 | public void run() {
135 | System.out.println("People["+name+"] is en en en...");
136 | try {
137 | Thread.sleep(new Random().nextInt(500));
138 | } catch (InterruptedException e) {
139 | e.printStackTrace();
140 | }
141 |
142 | toilet.enEn(name, new Random().nextInt(11));
143 | toilet.peopleOut(name);
144 | }
145 |
146 | }
147 |
148 | }
--------------------------------------------------------------------------------
/thread-examples/src/me/edagarli/uml/TestFlow.java:
--------------------------------------------------------------------------------
1 | package me.edagarli.uml;
2 |
3 | /**
4 | * User: edagarli
5 | * Email: lizhi@edagarli.com
6 | * Date: 16/5/11
7 | * Time: 12:59
8 | * Desc:
9 | */
10 | public class TestFlow {
11 | }
12 |
--------------------------------------------------------------------------------