diff --git a/.classpath b/.classpath deleted file mode 100644 index 83b76b7..0000000 --- a/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..6877a62 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,27 @@ +# EditorConfig helps developers define and maintain consistent +# coding styles between different editors and IDEs +# editorconfig.org + +root = true + +[*] + +# Change these settings to your own preference +indent_style = space +indent_size = 4 + +# We recommend you to keep these unchanged +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.md] +trim_trailing_whitespace = false + +[{package,bower}.json] +indent_style = space +indent_size = 2 + +[pom.xml] +indent_style = tab diff --git a/.gitignore b/.gitignore index a031ac2..c106db1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,13 +1,7 @@ -*.class - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.ear - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* -/bin/ +.idea/ +target/ +out/ +java-core-learning-example.iml +/java-core-learning-example.iml +/.idea/modules.xml +/.idea/vcs.xml diff --git a/.project b/.project deleted file mode 100644 index a636465..0000000 --- a/.project +++ /dev/null @@ -1,17 +0,0 @@ - - - java-core-learning - - - - - - org.eclipse.jdt.core.javabuilder - - - - - - org.eclipse.jdt.core.javanature - - diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs deleted file mode 100644 index 99f26c0..0000000 --- a/.settings/org.eclipse.core.resources.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -encoding/=UTF-8 diff --git a/README.md b/README.md index 3ac3870..318e499 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,60 @@ -# java-core-learning-example -关于Java核心技术学习积累的例子,是初学者及核心技术巩固的最佳实践。 +### 一、支持泥瓦匠 -## 作者与学习乐园 -源码地址:我的[GitHub地址](https://github.com/JeffLi1993 "GitHub")
-作者: [李强强](http://www.bysocket.com/ "李强强")
-QQ群:编程之美 365234583 [立即加入](http://jq.qq.com/?_wv=1027&k=Sx4s4U "编程之美") +关注泥瓦匠个人博客的更新:[我的博客](https://www.bysocket.com "我的博客") - 分享学习可落地的技术博文 -## 项目结构 +**Java 核心系列教程**,关于Java核心技术学习积累的例子,是初学者及核心技术巩固的最佳实践。 + +包括基础语法,OOP,字符串,集合,IO,反射,线程,网络等。 +未完成模块:阿里Java手册、java8,注解,fork/join,加解密等。欢迎fork,欢迎交流。 + +1. 拿起微信,关注公众号:「程序员泥瓦匠 」 +2. 给教程的开源代码仓库点个 **Star** 吧 + - [GitHub(java-core-learning-example)](https://github.com/JeffLi1993/java-core-learning-example) + - [Gitee(java-core-learning-example)](https://gitee.com/jeff1993/java-core-learning-example) +3. 帮忙分享该系列文章链接给更多的朋友 + +> 如果您对 Java 基础核心类教程不感冒或者想要通过综合案例学习Spring,那么给您推荐这个我觉得目前内容与价格最良心的视频课程:["玩转Spring全家桶"](https://time.geekbang.org/course/intro/156?code=zqaEuXYpWbKaPeBaJc8GVoYCUHvoGhTlQQ7QZYoWWdI%3D&utm_term=zeusDUJ0V&utm_source=website&utm_medium=bysocket ""玩转Spring全家桶"") + +### 二、系列文章目录 + +『 阿里 Java 开发手册篇 』 +- [《阿里 Java 手册系列教程:为啥强制子类、父类变量名不同?》](https://www.bysocket.com/technique/2253.html) +- [《阿里 Java 开发手册有感》](https://www.bysocket.com/technique/2210.html) + +『 Java 进阶篇 』 +- 连载中... + +『 Java 集合篇 』 +- [《Java 容器 & 泛型:一、认识容器》](http://www.bysocket.com/?p=162) +- [《Java 容器 & 泛型:二、ArrayList 、LinkedList和Vector比较》](http://www.bysocket.com/?p=169) +- [《Java 容器 & 泛型:三、HashSet,TreeSet 和 LinkedHashSet比较》](http://www.bysocket.com/?p=195) +- [《Java 容器 & 泛型:四、Colletions.sort 和 Arrays.sort 的算法》](http://www.bysocket.com/?p=219) +- [《Java 容器 & 泛型:五、HashMap 和 TreeMap的自白》](http://www.bysocket.com/?p=273) +- [《Java 容器 & 泛型:六、容器讲到为什么要使用泛型》](http://www.bysocket.com/?p=278) + +『 Java IO 篇 』 +- [《Java I/O : Bit Operation 位运算》](https://www.bysocket.com/?p=336) +- [《图解 Java IO : 一、File源码》](https://www.bysocket.com/?p=420) +- [《图解 Java IO : 二、FilenameFilter源码》](https://www.bysocket.com/?p=449) +- [《Java IO 之 InputStream源码》](https://www.bysocket.com/?p=585) +- [《Java IO 之 OutputStream源码》](https://www.bysocket.com/?p=592) +- [《Java IO 之 FileInputStream & FileOutputStream源码分析》](https://www.bysocket.com/?p=611) +- [《Java IO 总结图》](https://www.bysocket.com/?p=626) + + +### 三、最后推荐 + +- [我的博客](http://www.bysocket.com "我的博客"):分享学习可落地的技术博文 +- [我的GitHub](https://github.com/JeffLi1993 "我的GitHub"):Follow 下呗 +- [我的Gitee](https://gitee.com/jeff1993 "我的Gitee"):Follow 下呗 +- [Spring问答社区](http://www.spring4all.com/ "Spring问答社区"):如果您有什么问题,可以去这里发帖 + +### 四、我的公号 +关注微信公众号,领取 Java 精选干货学习资料 + + + +#### 项目结构 - src 目录
Java核心技术学习代码兼测试案例
- test目录(测试包名与src目录保持一致)
@@ -14,6 +62,9 @@ Java核心技术学习代码兼测试案例
包目录: + ├── org.rpc // 基于Java动态代理&Socket的简单RPC实现 + =================华丽的分割线================= + ├── org.javacore.base // Java基础必备 ├── org.javacore.collection // Java集合 ├── org.javacore.collection.list // Java集合List ├── org.javacore.collection.map // Java集合Map @@ -26,14 +77,22 @@ Java核心技术学习代码兼测试案例
├── org.javacore.io.zip // Java IO ZIP压缩解压 ├── org.javacore.nio // Java NIO ├── org.javacore.reflection // Java 反射 - ├── org.javacore.rtti // Java RTTI + ├── org.javacore.rtti // Java RTTI ├── org.javacore.thread // Java 线程 + =================实战JAVA 8================= + ├── org.javacore.lambda // lambda表达式 + ├── org.javacore.stream // Stream API 集合的流式操作 │ 拼命更新!顶!d=====( ̄▽ ̄*)b 详细目录: ├── README.md // 项目唯一详细文档 + ├── org.javacore.base // Java基础必备 + ├── CopyT.java // 深拷贝与浅拷贝 + ├── org.javacore.base.inter // Java接口 + ├── ApplyClass.java // 不使用接口的接口案例 + ├── ApplyInter.java // 使用接口的接口案例 ├── org.javacore.collection // Java集合 ├── PerBtwnAllCollectionsT.java // 各集合添加方法性能对比 ├── org.javacore.collection.list // Java集合List @@ -52,13 +111,13 @@ Java核心技术学习代码兼测试案例
├── SetContainT.java // Set的Contains方法 ├── TreeSetT.java // TreeSet操作实现Comparable接口的对象 ├── org.javacore.collection.util // Java集合工具类 - ├── CollectionsT.java // Collections的使用 + ├── CollectionsT.java // Collections的使用 ├── IterAndListIterT.java // Iterator与ListIterator的区别 ├── PerBtwnEmptyMapAndHashMapT.java // Collections.EMPTY_MAP 与 new HashMap 性能对比 ├── org.javacore.initAndCleanup // Java初始化及清理 ├── SimpleConstructor.java // 简单构造器的展示 ├── SimpleConstructor2.java // 带参数简单构造器的展示 - ├── VoidConstructor.java // 默认构造函数和方法的区别 + ├── VoidConstructor.java // 默认构造函数和方法的区别 ├── org.javacore.io // Java IO ├── BufferedInputFileT.java // 缓冲输入文件 ├── CopyFileT.java // 文件复制 @@ -100,6 +159,10 @@ Java核心技术学习代码兼测试案例
├── UsingBuffers.java // 利用buffer实现交换相邻字符 ├── ViewBuffers.java // 不同视图下的缓冲区 ├── org.javacore.reflection // Java 反射 + ├── ArrayCopy.java // 反射扩容对象数组 + ├── EmployeeClass.java // 反射在继承中的案例 + ├── ObjectAnalyzer.java // 反射对象分析工具 + ├── ReflectionTest.java // 反射对象构造函数、方法及字段 ├── User.java // 反射构造器使用的bean ├── UserConstructorReflect.java // 利用反射通过构造器创建一个实例 ├── org.javacore.rtti // Java RTTI @@ -109,19 +172,19 @@ Java核心技术学习代码兼测试案例
├── BasicThreads.java // 线程简单使用 ├── CachedThreadPool.java // 线程池CachedThreadPool的简单使用 ├── CallableDemo.java // Callable接口的使用 --- 实现带返回值的任务 - ├── DaemonFromFactory.java // 后台线程工厂类的使用 - ├── DaemonThreadFactory.java // 线程工厂类 - ├── DaemonsDontRunFinally.java // 后台线程遇到Finally + ├── DaemonFromFactory.java // 后台线程工厂类的使用 + ├── DaemonThreadFactory.java // 线程工厂类 + ├── DaemonsDontRunFinally.java // 后台线程遇到Finally ├── FixedThreadPool.java // 线程池FixedThreadPool的简单使用 ├── LiftOff.java // Runnable接口的实现类LiftOff ├── MoreBasicThreads.java // 线程简单使用-启动多个线程 ├── MyRunnable.java // Runnable接口的简单使用 ├── MyThread.java // Thread的简单使用 ├── SimpleDaemons.java // Daemon后台线程的简单使用 - ├── SimplePriorities.java // 线程优先级的使用 - ├── SingleThreadExecutor.java // SingleThreadExecutor的使用 - ├── SleepingTask.java // 休眠线程sleep的使用 + ├── SimplePriorities.java // 线程优先级的使用 + ├── SingleThreadExecutor.java // SingleThreadExecutor的使用 + ├── SleepingTask.java // 休眠线程sleep的使用 拼命更新!顶!d=====( ̄▽ ̄*)b - -##学习方法 + +#### 学习方法 根据包目录,进行一块一块学习。然后针对某类,请看下相对应的test包或者src下直接测试案例,进行学习。 diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..3b9d518 --- /dev/null +++ b/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + + org.javacore + java-core-learning-example + 0.0.1-SNAPSHOT + + java core learning example + java core learning example + war + + + 1.0 + + + + + com.google.collections + google-collections + ${google-collections.version} + + + + org.projectlombok + lombok + 1.16.8 + provided + + + + junit + junit + 4.12 + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + diff --git a/src/main/java/alibaba/java/ParentClass.java b/src/main/java/alibaba/java/ParentClass.java new file mode 100644 index 0000000..4c2379b --- /dev/null +++ b/src/main/java/alibaba/java/ParentClass.java @@ -0,0 +1,18 @@ +package alibaba.java; + +public class ParentClass { + public String name = "parent"; + + public static void main(String[] args) { + ParentClass parentClass = new SonClass(); + SonClass sonClass = new SonClass(); + + System.out.println("parentClass.name = " + parentClass.name); + System.out.println("sonClass.name = " + sonClass.name); + System.out.println("debug..."); + } +} + +class SonClass extends ParentClass { + public String name = "son"; +} diff --git a/src/main/java/org/javacore/base/String/StringT.java b/src/main/java/org/javacore/base/String/StringT.java new file mode 100644 index 0000000..cd26a67 --- /dev/null +++ b/src/main/java/org/javacore/base/String/StringT.java @@ -0,0 +1,34 @@ +package org.javacore.base.String; /* + * Copyright [2015] [Jeff Lee] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @author BYSocket + * @since 2016年01月06日 19:51:00 + * 常见面试题:String作为方法参数传递,另外一个例子 ${@link StringT2} + * 这就叫做"值传递",即方法操作的是参数变量(也就是原型变量的一个值的拷贝) + * 改变的也只是原型变量的一个拷贝而已,而非变量本身 + */ +public class StringT { + public static void main(String[] args) { + String str = "123"; + change(str); + System.out.println(str); + } + + public static void change(String str) { + str = "456"; + } +} diff --git a/src/main/java/org/javacore/base/String/StringT2.java b/src/main/java/org/javacore/base/String/StringT2.java new file mode 100644 index 0000000..2dc3d20 --- /dev/null +++ b/src/main/java/org/javacore/base/String/StringT2.java @@ -0,0 +1,47 @@ +package org.javacore.base.String; /* + * Copyright [2015] [Jeff Lee] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @author BYSocket + * @since 2016年01月06日 20:07:00 + * 对象含有String作为方法参数传递 + */ +public class StringT2 { + + public static void main(String[] args) { + StringObject sb = new StringObject(); + sb.setName("123"); + change(sb); + System.out.println(sb.getName()); + } + + public static void change(StringObject sb) { + sb = new StringObject(); + sb.setName("456"); + } + +} +class StringObject { + String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} \ No newline at end of file diff --git a/src/main/java/org/javacore/base/copy/CopyT.java b/src/main/java/org/javacore/base/copy/CopyT.java new file mode 100644 index 0000000..c52aec1 --- /dev/null +++ b/src/main/java/org/javacore/base/copy/CopyT.java @@ -0,0 +1,110 @@ +package org.javacore.base.copy; + +/* + * Copyright [2015] [Jeff Lee] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @author Jeff Lee + * @since 2015年11月16日 13:53:51 + * 深拷贝与浅拷贝 + */ +class Family implements Cloneable{ + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + /** + * 深拷贝 + * @return + */ + /*@Override + public Object clone() { + Object o = null; + try { + o = super.clone(); + } catch (CloneNotSupportedException e) { + e.printStackTrace(); + } + return o; + }*/ +} +class Student implements Cloneable{ + private String name; + private Family family; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Family getFamily() { + return family; + } + + public void setFamily(Family family) { + this.family = family; + } + + /** + * 浅拷贝 对其对象的引用却没有拷贝 + * @return + * @throws CloneNotSupportedException + */ + @Override + protected Object clone() throws CloneNotSupportedException { + return super.clone(); + } + + /** + * 深拷贝 + */ + /*@Override + protected Object clone() { + Student o = null; + try { + o = (Student)super.clone(); + } catch (CloneNotSupportedException e) { + e.printStackTrace(); + } + o.family = (Family) family.clone(); + return o; + }*/ +} + +public class CopyT { + public static void main(String[] args) throws CloneNotSupportedException { + Family family = new Family(); + family.setName("Jeff Family"); + Student student1 = new Student(); + student1.setFamily(family); + student1.setName("Jeff"); + + Student student2 = (Student) student1.clone(); + student2.setName("Jeff2"); + student2.getFamily().setName("Jeff2 Family"); + System.out.println(student1.getName() + " " + student1.getFamily().getName()); + System.out.println(student2.getName() + " " + student2.getFamily().getName()); + } +} \ No newline at end of file diff --git a/src/main/java/org/javacore/base/inter/ApplyClass.java b/src/main/java/org/javacore/base/inter/ApplyClass.java new file mode 100644 index 0000000..9d78a56 --- /dev/null +++ b/src/main/java/org/javacore/base/inter/ApplyClass.java @@ -0,0 +1,59 @@ +package org.javacore.base.inter; + +import java.util.Arrays; + +/* + * Copyright [2015] [Jeff Lee] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @author Jeff Lee + * @since 2015年12月1日 13:04:30 + * 不使用接口的接口案例 + */ +class Processor { + public String name(){ + return getClass().getSimpleName(); + } + + Object process(Object input){return input;} +} + +class Upcase extends Processor { + @Override + Object process(Object input) { + return ((String)input).toUpperCase(); + } +} + +class Splitcase extends Processor { + @Override + Object process(Object input) { + return Arrays.toString(((String) input).split(" ")); + } +} + +public class ApplyClass { + public static void process(Processor p , Object input){ + System.out.println("调用对象名:" + p.name()); + System.out.println(p.process(input)); + } + + public static String s = "BYSocket's Blog is www.bysocket.com"; + public static void main(String[] args) { + process(new Upcase(),s); + process(new Splitcase(),s); + } +} diff --git a/src/main/java/org/javacore/base/inter/ApplyInter.java b/src/main/java/org/javacore/base/inter/ApplyInter.java new file mode 100644 index 0000000..e63a70a --- /dev/null +++ b/src/main/java/org/javacore/base/inter/ApplyInter.java @@ -0,0 +1,67 @@ +package org.javacore.base.inter; + +import java.util.Arrays; + +/* + * Copyright [2015] [Jeff Lee] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @author Jeff Lee + * @since 2015年12月1日 13:04:30 + * 使用接口的接口案例 + */ +interface ProcessorInter { + String name(); + + Object process(Object input); +} + +class UpcaseImpl implements ProcessorInter { + @Override + public String name() { + return this.getClass().getSimpleName(); + } + + @Override + public Object process(Object input) { + return ((String)input).toUpperCase(); + } +} + +class SplitcaseImpl implements ProcessorInter { + @Override + public String name() { + return this.getClass().getSimpleName(); + } + + @Override + public Object process(Object input) { + return Arrays.toString(((String) input).split(" ")); + } +} + +public class ApplyInter { + public static void process(ProcessorInter p , Object input){ + System.out.println("调用对象名:" + p.name()); + System.out.println(p.process(input)); + } + + public static String s = "BYSocket's Blog is www.bysocket.com"; + public static void main(String[] args) { + process(new UpcaseImpl(),s); + process(new SplitcaseImpl(),s); + } +} diff --git a/src/main/java/org/javacore/colgoogle/MapMakerT.java b/src/main/java/org/javacore/colgoogle/MapMakerT.java new file mode 100644 index 0000000..a1b8b99 --- /dev/null +++ b/src/main/java/org/javacore/colgoogle/MapMakerT.java @@ -0,0 +1,33 @@ +package org.javacore.colgoogle; + +import com.google.common.base.Function; +import com.google.common.collect.MapMaker; + +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.TimeUnit; + +/** + * Created by 子木 on 2016年2月20日. + */ +public class MapMakerT { + // 使用案例:存储验证码 + // == <用户唯一,验证码> + // expiration(15, TimeUnit.MINUTES) 有效期15分钟 + ConcurrentMap capthcaMap = new MapMaker().expiration(15, TimeUnit.MINUTES).makeMap(); + + // 设置ConcurrentMap的concurrencyLevel参数 ,例如ConcurrentHashMap是用来控制其Segment数组的大小 + ConcurrentMap map1 = new MapMaker().concurrencyLevel(8).makeMap(); + + // 构造各种不同reference作为key和value的map + ConcurrentMap map2 = new MapMaker().softKeys().weakValues().makeMap(); + + // 提供当Map里面不包含所get的项,可以自动加入到Map的功能 + ConcurrentMap map3 = new MapMaker() + .makeComputingMap( + new Function() { + public Integer apply(String key) { + return 1; + } + } + ); +} diff --git a/src/main/java/org/javacore/colgoogle/MapMakerT0.java b/src/main/java/org/javacore/colgoogle/MapMakerT0.java new file mode 100644 index 0000000..56bc9b7 --- /dev/null +++ b/src/main/java/org/javacore/colgoogle/MapMakerT0.java @@ -0,0 +1,48 @@ +package org.javacore.colgoogle; + +import com.google.common.base.Function; +import com.google.common.collect.MapMaker; + +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.TimeUnit; + +/** + * Created by 子木 on 2016年2月20日. + */ +public class MapMakerT0 { + public static void main(String[] args) { + /** + * expiration(3, TimeUnit.SECONDS)设置超时时间为3秒 + */ + ConcurrentMap map = new MapMaker().concurrencyLevel(32).softKeys().weakValues() + .expiration(3, TimeUnit.SECONDS).makeComputingMap( + /** + * 提供当Map里面不包含所get的项,可以自动加入到Map的功能 + * 可以将这里的返回值放到对应的key的value中 + */ + new Function() { + public String apply(String s) { + return "creating " + s + " -> Object"; + } + } + ); + + map.put("a","testa"); + map.put("b","testb"); + + System.out.println(map.get("a")); + System.out.println(map.get("b")); + System.out.println(map.get("c")); + + try { + // 4秒后,大于超时时间,缓存失效。 + Thread.sleep(4000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + System.out.println(map.get("a")); + System.out.println(map.get("b")); + System.out.println(map.get("c")); + } +} diff --git a/src/org/javacore/collection/PerBtwnAllCollectionsT.java b/src/main/java/org/javacore/collection/PerBtwnAllCollectionsT.java similarity index 100% rename from src/org/javacore/collection/PerBtwnAllCollectionsT.java rename to src/main/java/org/javacore/collection/PerBtwnAllCollectionsT.java diff --git a/src/main/java/org/javacore/collection/hash/HashList.java b/src/main/java/org/javacore/collection/hash/HashList.java new file mode 100644 index 0000000..06bb5b1 --- /dev/null +++ b/src/main/java/org/javacore/collection/hash/HashList.java @@ -0,0 +1,35 @@ +package org.javacore.collection.hash; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by bysocket on 16/9/26. + */ +public class HashList { + public static void main(String[] args) { + // init data list + List reqSkuObjList = new ArrayList(); + List existSkuObjList = new ArrayList(); + for (int i = 0 ; i < 5000; i++) { + SkuObj skuObj = new SkuObj(); + skuObj.setId(i); + skuObj.setName("name" + i); + skuObj.setAge(i + 666); + skuObj.setDesc("desc" + i); + reqSkuObjList.add(skuObj); + } + + for (int i = 0 ; i < 5000; i++) { + SkuObj skuObj = new SkuObj(); + skuObj.setId(i); + skuObj.setName("nameexist" + i); + skuObj.setAge(i + 888); + skuObj.setDesc("descexist" + i); + existSkuObjList.add(skuObj); + } + + + + } +} diff --git a/src/main/java/org/javacore/collection/hash/SkuObj.java b/src/main/java/org/javacore/collection/hash/SkuObj.java new file mode 100644 index 0000000..50edd04 --- /dev/null +++ b/src/main/java/org/javacore/collection/hash/SkuObj.java @@ -0,0 +1,47 @@ +package org.javacore.collection.hash; + +/** + * Created by bysocket on 16/9/26. + */ +public class SkuObj { + + Integer id; + + String name; + + Integer age; + + String desc; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } +} diff --git a/src/org/javacore/collection/list/ArrayListT.java b/src/main/java/org/javacore/collection/list/ArrayListT.java similarity index 100% rename from src/org/javacore/collection/list/ArrayListT.java rename to src/main/java/org/javacore/collection/list/ArrayListT.java diff --git a/src/main/java/org/javacore/collection/list/ListT0.java b/src/main/java/org/javacore/collection/list/ListT0.java new file mode 100644 index 0000000..802e34a --- /dev/null +++ b/src/main/java/org/javacore/collection/list/ListT0.java @@ -0,0 +1,50 @@ +package org.javacore.collection.list; /* + * Copyright [2015] [Jeff Lee] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.ArrayList; +import java.util.List; +import java.util.ListIterator; + +/** + * @author BYSocket + * @since 2016-01-06 20:11:00 + * 打印list 全部元素,并找到其中元素aaa删除。要求:所有元素都遍历完 + * ListIterator 的使用 + * list那个remove回抛异常是因为快速失败的机制, + * 他内置了一个modifyCount的变量记录list的长度变化,用Iter可以删除掉 + */ +public class ListT0 { + public static void main(String[] args) { + List list =new ArrayList(); + list.add("1"); + list.add("2"); + list.add("3"); + list.add("4"); + list.add("aaa"); + list.add("6"); + list.add("7"); + + ListIterator listIterator = list.listIterator(); + while (listIterator.hasNext()) { + Object o = listIterator.next(); + System.out.println(o); + if (o.equals("aaa")) { + listIterator.remove(); + } + } + } + +} diff --git a/src/org/javacore/collection/list/PerBtwnArlAndLklT.java b/src/main/java/org/javacore/collection/list/PerBtwnArlAndLklT.java similarity index 100% rename from src/org/javacore/collection/list/PerBtwnArlAndLklT.java rename to src/main/java/org/javacore/collection/list/PerBtwnArlAndLklT.java diff --git a/src/org/javacore/collection/map/HashMapObjT.java b/src/main/java/org/javacore/collection/map/HashMapObjT.java similarity index 100% rename from src/org/javacore/collection/map/HashMapObjT.java rename to src/main/java/org/javacore/collection/map/HashMapObjT.java diff --git a/src/org/javacore/collection/map/HaspMapT.java b/src/main/java/org/javacore/collection/map/HaspMapT.java similarity index 100% rename from src/org/javacore/collection/map/HaspMapT.java rename to src/main/java/org/javacore/collection/map/HaspMapT.java diff --git a/src/org/javacore/collection/map/TreeMapT.java b/src/main/java/org/javacore/collection/map/TreeMapT.java similarity index 100% rename from src/org/javacore/collection/map/TreeMapT.java rename to src/main/java/org/javacore/collection/map/TreeMapT.java diff --git a/src/org/javacore/collection/queue/PriorityQueueT.java b/src/main/java/org/javacore/collection/queue/PriorityQueueT.java similarity index 100% rename from src/org/javacore/collection/queue/PriorityQueueT.java rename to src/main/java/org/javacore/collection/queue/PriorityQueueT.java diff --git a/src/org/javacore/collection/set/HashSetObjT.java b/src/main/java/org/javacore/collection/set/HashSetObjT.java similarity index 100% rename from src/org/javacore/collection/set/HashSetObjT.java rename to src/main/java/org/javacore/collection/set/HashSetObjT.java diff --git a/src/org/javacore/collection/set/HashSetT.java b/src/main/java/org/javacore/collection/set/HashSetT.java similarity index 100% rename from src/org/javacore/collection/set/HashSetT.java rename to src/main/java/org/javacore/collection/set/HashSetT.java diff --git a/src/org/javacore/collection/set/HashSetsCopyT.java b/src/main/java/org/javacore/collection/set/HashSetsCopyT.java similarity index 100% rename from src/org/javacore/collection/set/HashSetsCopyT.java rename to src/main/java/org/javacore/collection/set/HashSetsCopyT.java diff --git a/src/org/javacore/collection/set/SetContainT.java b/src/main/java/org/javacore/collection/set/SetContainT.java similarity index 100% rename from src/org/javacore/collection/set/SetContainT.java rename to src/main/java/org/javacore/collection/set/SetContainT.java diff --git a/src/org/javacore/collection/set/TreeSetT.java b/src/main/java/org/javacore/collection/set/TreeSetT.java similarity index 100% rename from src/org/javacore/collection/set/TreeSetT.java rename to src/main/java/org/javacore/collection/set/TreeSetT.java diff --git a/src/org/javacore/collection/util/CollectionsT.java b/src/main/java/org/javacore/collection/util/CollectionsT.java similarity index 64% rename from src/org/javacore/collection/util/CollectionsT.java rename to src/main/java/org/javacore/collection/util/CollectionsT.java index 06ea412..b7f0b22 100644 --- a/src/org/javacore/collection/util/CollectionsT.java +++ b/src/main/java/org/javacore/collection/util/CollectionsT.java @@ -28,21 +28,33 @@ public class CollectionsT{ public static void main(String[] args){ // 测试集合工具类Sort方法 testSort(); + testAddAll(); } /** * 测试集合工具类Sort方法 */ - private static void testSort(){ - List teams = new ArrayList(); - teams.add(1); - teams.add(3); - teams.add(2); - teams.add(4); - // 调用集合工具类Sort方法 - Collections.sort(teams); - - System.out.println("Teams:"); - System.out.print("\t" + teams + "\n"); - } +private static void testSort(){ + List list = new ArrayList(); + list.add(1); + list.add(3); + list.add(2); + list.add(4); + // 调用集合工具类Sort方法 + Collections.sort(list); + + System.out.println("list sorted:"); + System.out.print("\t" + list + "\n"); +} + +private static void testAddAll() { + List list = new ArrayList(); + list.add("s2"); + list.add("s4"); + list.add("s1"); + list.add("s3"); + System.out.println(list); + Collections.addAll(list, "s5","s7",null,"s9"); + System.out.println(list); +} } diff --git a/src/org/javacore/collection/util/IterAndListIterT.java b/src/main/java/org/javacore/collection/util/IterAndListIterT.java similarity index 100% rename from src/org/javacore/collection/util/IterAndListIterT.java rename to src/main/java/org/javacore/collection/util/IterAndListIterT.java diff --git a/src/org/javacore/collection/util/PerBtwnEmptyMapAndHashMapT.java b/src/main/java/org/javacore/collection/util/PerBtwnEmptyMapAndHashMapT.java similarity index 100% rename from src/org/javacore/collection/util/PerBtwnEmptyMapAndHashMapT.java rename to src/main/java/org/javacore/collection/util/PerBtwnEmptyMapAndHashMapT.java diff --git a/src/main/java/org/javacore/concurrent/CountDownLatchT.java b/src/main/java/org/javacore/concurrent/CountDownLatchT.java new file mode 100644 index 0000000..34e6677 --- /dev/null +++ b/src/main/java/org/javacore/concurrent/CountDownLatchT.java @@ -0,0 +1,48 @@ +package org.javacore.concurrent; + +import java.util.Random; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +/** + * 同步辅助类:完成一组线程执行前,使得一个或多个线程一直等待 + * + * Created by bysocket on 16/4/26. + */ +public class CountDownLatchT { + + // 线程中止的计数器 + private final static int COUNT = 10; + private final static CountDownLatch count = new CountDownLatch(COUNT); + + // 线程池 + private final static ExecutorService service = Executors.newFixedThreadPool(5); + + public static void main(String[] args) throws InterruptedException { + for (int i = 0; i < COUNT; i++) { + service.execute(() -> { + try { + int time = new Random().nextInt(5); + TimeUnit.SECONDS.sleep(time); + System.out.printf("Thread %s ## 耗时:%d\n", Thread.currentThread().getId(), time); + // 线程结束后,计数器减一 + count.countDown(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + }); + } + + // 主线程一直被阻塞,直到count为0,实现线程同步 + count.await(); + service.shutdown(); + + System.out.println("同步线程执行组结束!"); + + } +} + + diff --git a/src/main/java/org/javacore/img/ImgCircleCut.java b/src/main/java/org/javacore/img/ImgCircleCut.java new file mode 100644 index 0000000..ecb5bf9 --- /dev/null +++ b/src/main/java/org/javacore/img/ImgCircleCut.java @@ -0,0 +1,60 @@ +package org.javacore.img; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.geom.Ellipse2D; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +/* + * Copyright [2015] [Jeff Lee] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @author Jeff Lee + * @since 2016年06月28日 14:05:26 + * 图片裁成椭圆 + */ +public class ImgCircleCut { + + public static boolean ImgCircleCut(String srcFile, String targetFile) { + try { + // 获取img的BufferedImage对象,可以考虑创建不带透明色的BufferedImage对象:BufferedImage.TYPE_INT_ARGB + BufferedImage srcBi = ImageIO.read(new File(srcFile)); + // 创建一个带透明色的BufferedImage对象 + BufferedImage targetBi = new BufferedImage(srcBi.getWidth(), srcBi.getHeight(), + BufferedImage.TYPE_INT_ARGB); + // 获取img窗体矩形定义的椭圆 + Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, + srcBi.getWidth(), srcBi.getHeight()); + // 创建目标图的Graphics2D对象 + Graphics2D g2 = targetBi.createGraphics(); + // 创建不透明 SRC_OVER 规则的 AlphaComposite 对象 + AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.9f); + g2.setComposite(ac); + g2.setBackground(new Color(22, 2, 2, 0)); + // 是圆形 还是 椭圆 自定义参数 + g2.fill3DRect(200, 200, 180, 80, false); + g2.setClip(shape); + g2.drawImage(srcBi, 0, 0, null); + g2.dispose(); + ImageIO.write(targetBi, "png", new File(targetFile)); + } catch (IOException e) { + e.printStackTrace(); + return false; + } + return true; + } +} diff --git a/src/org/javacore/initAndCleanup/SimpleConstructor.java b/src/main/java/org/javacore/initAndCleanup/SimpleConstructor.java similarity index 100% rename from src/org/javacore/initAndCleanup/SimpleConstructor.java rename to src/main/java/org/javacore/initAndCleanup/SimpleConstructor.java diff --git a/src/org/javacore/initAndCleanup/SimpleConstructor2.java b/src/main/java/org/javacore/initAndCleanup/SimpleConstructor2.java similarity index 100% rename from src/org/javacore/initAndCleanup/SimpleConstructor2.java rename to src/main/java/org/javacore/initAndCleanup/SimpleConstructor2.java diff --git a/src/org/javacore/initAndCleanup/VoidConstructor.java b/src/main/java/org/javacore/initAndCleanup/VoidConstructor.java similarity index 100% rename from src/org/javacore/initAndCleanup/VoidConstructor.java rename to src/main/java/org/javacore/initAndCleanup/VoidConstructor.java diff --git a/src/org/javacore/io/BufferedInputFileT.java b/src/main/java/org/javacore/io/BufferedInputFileT.java similarity index 100% rename from src/org/javacore/io/BufferedInputFileT.java rename to src/main/java/org/javacore/io/BufferedInputFileT.java diff --git a/src/org/javacore/io/ChangeSystemOut.java b/src/main/java/org/javacore/io/ChangeSystemOut.java similarity index 100% rename from src/org/javacore/io/ChangeSystemOut.java rename to src/main/java/org/javacore/io/ChangeSystemOut.java diff --git a/src/org/javacore/io/CopyFileT.java b/src/main/java/org/javacore/io/CopyFileT.java similarity index 100% rename from src/org/javacore/io/CopyFileT.java rename to src/main/java/org/javacore/io/CopyFileT.java diff --git a/src/org/javacore/io/DirListT.java b/src/main/java/org/javacore/io/DirListT.java similarity index 100% rename from src/org/javacore/io/DirListT.java rename to src/main/java/org/javacore/io/DirListT.java diff --git a/src/org/javacore/io/Directory.java b/src/main/java/org/javacore/io/Directory.java similarity index 100% rename from src/org/javacore/io/Directory.java rename to src/main/java/org/javacore/io/Directory.java diff --git a/src/org/javacore/io/FileIOStreamT.java b/src/main/java/org/javacore/io/FileIOStreamT.java similarity index 100% rename from src/org/javacore/io/FileIOStreamT.java rename to src/main/java/org/javacore/io/FileIOStreamT.java diff --git a/src/org/javacore/io/FileMethodsT.java b/src/main/java/org/javacore/io/FileMethodsT.java similarity index 100% rename from src/org/javacore/io/FileMethodsT.java rename to src/main/java/org/javacore/io/FileMethodsT.java diff --git a/src/org/javacore/io/FileT.java b/src/main/java/org/javacore/io/FileT.java similarity index 100% rename from src/org/javacore/io/FileT.java rename to src/main/java/org/javacore/io/FileT.java diff --git a/src/org/javacore/io/FilenameFilterT.java b/src/main/java/org/javacore/io/FilenameFilterT.java similarity index 100% rename from src/org/javacore/io/FilenameFilterT.java rename to src/main/java/org/javacore/io/FilenameFilterT.java diff --git a/src/org/javacore/io/FormatteMemoryInput.java b/src/main/java/org/javacore/io/FormatteMemoryInput.java similarity index 100% rename from src/org/javacore/io/FormatteMemoryInput.java rename to src/main/java/org/javacore/io/FormatteMemoryInput.java diff --git a/src/org/javacore/io/JavaFileListT.java b/src/main/java/org/javacore/io/JavaFileListT.java similarity index 100% rename from src/org/javacore/io/JavaFileListT.java rename to src/main/java/org/javacore/io/JavaFileListT.java diff --git a/src/org/javacore/io/MemoryInputT.java b/src/main/java/org/javacore/io/MemoryInputT.java similarity index 100% rename from src/org/javacore/io/MemoryInputT.java rename to src/main/java/org/javacore/io/MemoryInputT.java diff --git a/src/org/javacore/io/OSExecuteT.java b/src/main/java/org/javacore/io/OSExecuteT.java similarity index 100% rename from src/org/javacore/io/OSExecuteT.java rename to src/main/java/org/javacore/io/OSExecuteT.java diff --git a/src/org/javacore/io/PipeStreamT.java b/src/main/java/org/javacore/io/PipeStreamT.java similarity index 100% rename from src/org/javacore/io/PipeStreamT.java rename to src/main/java/org/javacore/io/PipeStreamT.java diff --git a/src/org/javacore/io/RandomAccessFileT.java b/src/main/java/org/javacore/io/RandomAccessFileT.java similarity index 100% rename from src/org/javacore/io/RandomAccessFileT.java rename to src/main/java/org/javacore/io/RandomAccessFileT.java diff --git a/src/org/javacore/io/SByteArrayInputStream.java b/src/main/java/org/javacore/io/SByteArrayInputStream.java similarity index 100% rename from src/org/javacore/io/SByteArrayInputStream.java rename to src/main/java/org/javacore/io/SByteArrayInputStream.java diff --git a/src/org/javacore/io/SFileInputStream.java b/src/main/java/org/javacore/io/SFileInputStream.java similarity index 100% rename from src/org/javacore/io/SFileInputStream.java rename to src/main/java/org/javacore/io/SFileInputStream.java diff --git a/src/org/javacore/io/SFileOutputStream.java b/src/main/java/org/javacore/io/SFileOutputStream.java similarity index 100% rename from src/org/javacore/io/SFileOutputStream.java rename to src/main/java/org/javacore/io/SFileOutputStream.java diff --git a/src/org/javacore/io/SInputStream.java b/src/main/java/org/javacore/io/SInputStream.java similarity index 100% rename from src/org/javacore/io/SInputStream.java rename to src/main/java/org/javacore/io/SInputStream.java diff --git a/src/org/javacore/io/SOutputStream.java b/src/main/java/org/javacore/io/SOutputStream.java similarity index 100% rename from src/org/javacore/io/SOutputStream.java rename to src/main/java/org/javacore/io/SOutputStream.java diff --git a/src/org/javacore/io/StoringAndRecoveringData.java b/src/main/java/org/javacore/io/StoringAndRecoveringData.java similarity index 100% rename from src/org/javacore/io/StoringAndRecoveringData.java rename to src/main/java/org/javacore/io/StoringAndRecoveringData.java diff --git a/src/org/javacore/io/SystemStreamT.java b/src/main/java/org/javacore/io/SystemStreamT.java similarity index 100% rename from src/org/javacore/io/SystemStreamT.java rename to src/main/java/org/javacore/io/SystemStreamT.java diff --git a/src/org/javacore/io/TextFile.java b/src/main/java/org/javacore/io/TextFile.java similarity index 100% rename from src/org/javacore/io/TextFile.java rename to src/main/java/org/javacore/io/TextFile.java diff --git a/src/org/javacore/io/UsingRandomAccessFile.java b/src/main/java/org/javacore/io/UsingRandomAccessFile.java similarity index 100% rename from src/org/javacore/io/UsingRandomAccessFile.java rename to src/main/java/org/javacore/io/UsingRandomAccessFile.java diff --git a/src/org/javacore/io/byteoper/IntegerConvertT.java b/src/main/java/org/javacore/io/byteoper/IntegerConvertT.java similarity index 100% rename from src/org/javacore/io/byteoper/IntegerConvertT.java rename to src/main/java/org/javacore/io/byteoper/IntegerConvertT.java diff --git a/src/org/javacore/io/byteoper/IntegerOperT.java b/src/main/java/org/javacore/io/byteoper/IntegerOperT.java similarity index 100% rename from src/org/javacore/io/byteoper/IntegerOperT.java rename to src/main/java/org/javacore/io/byteoper/IntegerOperT.java diff --git a/src/org/javacore/io/byteoper/LongConvertT.java b/src/main/java/org/javacore/io/byteoper/LongConvertT.java similarity index 100% rename from src/org/javacore/io/byteoper/LongConvertT.java rename to src/main/java/org/javacore/io/byteoper/LongConvertT.java diff --git a/src/org/javacore/io/byteoper/StringConvertT.java b/src/main/java/org/javacore/io/byteoper/StringConvertT.java similarity index 78% rename from src/org/javacore/io/byteoper/StringConvertT.java rename to src/main/java/org/javacore/io/byteoper/StringConvertT.java index a8189f8..b732f61 100644 --- a/src/org/javacore/io/byteoper/StringConvertT.java +++ b/src/main/java/org/javacore/io/byteoper/StringConvertT.java @@ -5,9 +5,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,11 +23,12 @@ public class StringConvertT { public static void main(String[] args){ - String str = "李强强"; + String str = "HOME"; byte[] bytes = str.getBytes(); // 打印字节数组 - System.out.println("UTF-8编码'李强强'的字节数组为:"); - for (int i = 0; i < bytes.length; i++) - System.out.print("\t" + bytes[i]); + System.out.println("UTF-8编码'HOME'的字节数组为:"); + for (int i = 0; i < bytes.length; i++) { + System.out.println("\t" + bytes[i] + "|" + Integer.toBinaryString(bytes[i])); + } } } diff --git a/src/main/java/org/javacore/io/serializable/SerializableT.java b/src/main/java/org/javacore/io/serializable/SerializableT.java new file mode 100644 index 0000000..32c9197 --- /dev/null +++ b/src/main/java/org/javacore/io/serializable/SerializableT.java @@ -0,0 +1,60 @@ +package org.javacore.io.serializable; + + +//import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream; +// +//import java.io.*; +// +///** +// * 描述:Java序列化和反序列化的小例子 +// * Created by 子木 on 2016/2/15. +// */ +//public class SerializableT { +// public static void main(String[] args) throws IOException, ClassNotFoundException { +// for (int i = 0;i < 10;i++) { +// AObjcet aObjcet = new AObjcet(); +// long beginTime = System.currentTimeMillis(); +// +// ByteOutputStream byteOutput = new ByteOutputStream(); +// ObjectOutputStream objectOutput = new ObjectOutputStream(byteOutput); +// objectOutput.writeObject(aObjcet); +// objectOutput.close(); +// byteOutput.close(); +// byte[] bytes = byteOutput.toByteArray(); +// System.out.println("Java序列化耗时:" + (System.currentTimeMillis() - beginTime) + "ms"); +// System.out.println("Java序列化后的字节大小为:" + bytes.length); +// +// beginTime = System.currentTimeMillis(); +// ByteArrayInputStream byteInput = new ByteArrayInputStream(bytes); +// ObjectInputStream objectInput = new ObjectInputStream(byteInput); +// objectInput.readObject(); +// objectInput.close(); +// byteInput.close(); +// System.out.println("Java反序列化耗时:" + (System.currentTimeMillis() - beginTime) + "ms"); +// +// } +// } +//} +//class AObjcet implements Serializable { +// private String a = "bysocket"; +// private String b = "likes"; +// private String c = "java"; +// private String d = "world"; +// +// private int i = 100; +// private int j = 10; +// private long m = 100L; +// +// private boolean isA = true; +// private boolean isB = false; +// private boolean isC = false; +// +// private BObject aObject = new BObject(); +// private BObject bObject = new BObject(); +// private BObject cObject = new BObject(); +// private BObject dObject = new BObject(); +// +//} +//class BObject implements Serializable { +// +//} diff --git a/src/org/javacore/io/zip/GZIPcompress.java b/src/main/java/org/javacore/io/zip/GZIPcompress.java similarity index 100% rename from src/org/javacore/io/zip/GZIPcompress.java rename to src/main/java/org/javacore/io/zip/GZIPcompress.java diff --git a/src/org/javacore/io/zip/ZipCompress.java b/src/main/java/org/javacore/io/zip/ZipCompress.java similarity index 100% rename from src/org/javacore/io/zip/ZipCompress.java rename to src/main/java/org/javacore/io/zip/ZipCompress.java diff --git a/src/main/java/org/javacore/lambda/LambdaListCompare.java b/src/main/java/org/javacore/lambda/LambdaListCompare.java new file mode 100644 index 0000000..1afc67f --- /dev/null +++ b/src/main/java/org/javacore/lambda/LambdaListCompare.java @@ -0,0 +1,59 @@ +package org.javacore.lambda; + +/* + * Copyright [2015] [Jeff Lee] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.ArrayList; +import java.util.List; + +/** + * List 比较器 + * + * Created by bysocket on 16/7/12. + */ +public class LambdaListCompare { + public static void main(String[] args) { + List list = new ArrayList(); + list.add(4); + list.add(1); + list.add(3); + list.add(6); + +// list.sort(new Comparator() { +// @Override +// public int compare(Integer o1, Integer o2) { +// return Integer.compare(o1, o2); +// } +// }); + + /** Lambda表达式格式: + * (Type1 param1, Type2 param2, ..., TypeN paramN) -> { + * statment1; + * statment2; + * ... + * return statmentM; + * } + */ +// list.sort(((o1, o2) -> { +// return Integer.compare(o1, o2); +// })); + + // 简写Lambda表达式 + list.sort((o1, o2) -> Integer.compare(o1, o2)); + + System.out.println(list.toString()); + } +} diff --git a/src/main/java/org/javacore/lambda/LambdaOperators.java b/src/main/java/org/javacore/lambda/LambdaOperators.java new file mode 100644 index 0000000..85dfde1 --- /dev/null +++ b/src/main/java/org/javacore/lambda/LambdaOperators.java @@ -0,0 +1,51 @@ +package org.javacore.lambda; + +/* + * Copyright [2015] [Jeff Lee] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +/** + * Lambda 操作符 + * + * Created by bysocket on 16/7/13. + */ +public class LambdaOperators { + public static void main(String[] args) { + List list = new ArrayList(); + list.add("aaa"); + list.add("cccc"); + list.add("b"); + list.add("eeeee"); + + /** + * :: 操作符格式 => 三种情况 + * 对象::实例方法 + * 类::静态方法 + * 类::实例方法 对于前两种情况,方法引用就是对参数执行该方法。比如下面两种方法 + */ + // 按字符串大小排序忽略大小写 + list.sort(String::compareToIgnoreCase); + // 打印 list 元素 + list.forEach(System.out::println); + + System.out.println("======按字符大小排序======"); + list.sort(Comparator.comparing(String::length)); + list.forEach(System.out::println); + } +} diff --git a/src/main/java/org/javacore/lambda/LambdaRunnable.java b/src/main/java/org/javacore/lambda/LambdaRunnable.java new file mode 100644 index 0000000..9cf408a --- /dev/null +++ b/src/main/java/org/javacore/lambda/LambdaRunnable.java @@ -0,0 +1,45 @@ +package org.javacore.lambda; + +/* + * Copyright [2015] [Jeff Lee] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Lambda - 启动线程 + * + * Created by bysocket on 16/7/13. + */ +public class LambdaRunnable { + static int b = 10; + + public static void main(String[] args) { + // 启动线程 +// Thread thread = new Thread(new Runnable() { +// @Override +// public void run() { +// b++; +// System.out.println(b); +// } +// }); + + // Lambda - 启动线程 + Thread thread = new Thread(() -> { + b++; + System.out.println(b); + }); + thread.start(); + System.out.println("Done!"); + } +} diff --git a/src/org/javacore/nio/AvailableCharSets.java b/src/main/java/org/javacore/nio/AvailableCharSets.java similarity index 100% rename from src/org/javacore/nio/AvailableCharSets.java rename to src/main/java/org/javacore/nio/AvailableCharSets.java diff --git a/src/org/javacore/nio/BufferToText.java b/src/main/java/org/javacore/nio/BufferToText.java similarity index 100% rename from src/org/javacore/nio/BufferToText.java rename to src/main/java/org/javacore/nio/BufferToText.java diff --git a/src/org/javacore/nio/ChannelCopy.java b/src/main/java/org/javacore/nio/ChannelCopy.java similarity index 100% rename from src/org/javacore/nio/ChannelCopy.java rename to src/main/java/org/javacore/nio/ChannelCopy.java diff --git a/src/org/javacore/nio/Endians.java b/src/main/java/org/javacore/nio/Endians.java similarity index 100% rename from src/org/javacore/nio/Endians.java rename to src/main/java/org/javacore/nio/Endians.java diff --git a/src/org/javacore/nio/FileChannelT.java b/src/main/java/org/javacore/nio/FileChannelT.java similarity index 100% rename from src/org/javacore/nio/FileChannelT.java rename to src/main/java/org/javacore/nio/FileChannelT.java diff --git a/src/org/javacore/nio/FileChannelTransferTo.java b/src/main/java/org/javacore/nio/FileChannelTransferTo.java similarity index 100% rename from src/org/javacore/nio/FileChannelTransferTo.java rename to src/main/java/org/javacore/nio/FileChannelTransferTo.java diff --git a/src/org/javacore/nio/FileLocking.java b/src/main/java/org/javacore/nio/FileLocking.java similarity index 100% rename from src/org/javacore/nio/FileLocking.java rename to src/main/java/org/javacore/nio/FileLocking.java diff --git a/src/org/javacore/nio/GetChannel.java b/src/main/java/org/javacore/nio/GetChannel.java similarity index 100% rename from src/org/javacore/nio/GetChannel.java rename to src/main/java/org/javacore/nio/GetChannel.java diff --git a/src/org/javacore/nio/GetData.java b/src/main/java/org/javacore/nio/GetData.java similarity index 100% rename from src/org/javacore/nio/GetData.java rename to src/main/java/org/javacore/nio/GetData.java diff --git a/src/org/javacore/nio/IntBufferDemo.java b/src/main/java/org/javacore/nio/IntBufferDemo.java similarity index 100% rename from src/org/javacore/nio/IntBufferDemo.java rename to src/main/java/org/javacore/nio/IntBufferDemo.java diff --git a/src/org/javacore/nio/LargeMappedFiles.java b/src/main/java/org/javacore/nio/LargeMappedFiles.java similarity index 100% rename from src/org/javacore/nio/LargeMappedFiles.java rename to src/main/java/org/javacore/nio/LargeMappedFiles.java diff --git a/src/org/javacore/nio/LockingMappedFiles.java b/src/main/java/org/javacore/nio/LockingMappedFiles.java similarity index 100% rename from src/org/javacore/nio/LockingMappedFiles.java rename to src/main/java/org/javacore/nio/LockingMappedFiles.java diff --git a/src/org/javacore/nio/MappedIO.java b/src/main/java/org/javacore/nio/MappedIO.java similarity index 100% rename from src/org/javacore/nio/MappedIO.java rename to src/main/java/org/javacore/nio/MappedIO.java diff --git a/src/org/javacore/nio/UsingBuffers.java b/src/main/java/org/javacore/nio/UsingBuffers.java similarity index 100% rename from src/org/javacore/nio/UsingBuffers.java rename to src/main/java/org/javacore/nio/UsingBuffers.java diff --git a/src/org/javacore/nio/ViewBuffers.java b/src/main/java/org/javacore/nio/ViewBuffers.java similarity index 100% rename from src/org/javacore/nio/ViewBuffers.java rename to src/main/java/org/javacore/nio/ViewBuffers.java diff --git a/src/main/java/org/javacore/reflection/ArrayCopy.java b/src/main/java/org/javacore/reflection/ArrayCopy.java new file mode 100644 index 0000000..e68b396 --- /dev/null +++ b/src/main/java/org/javacore/reflection/ArrayCopy.java @@ -0,0 +1,51 @@ +package org.javacore.reflection; + +import java.lang.reflect.Array; +import java.util.Arrays; + +/* + * Copyright [2015] [Jeff Lee] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @author Jeff Lee + * @since 2015年11月9日 10:45:19 + * 反射扩容对象数组 + */ +public class ArrayCopy { + public static void main(String[] args) { + int[] a = {1,2,3}; + a = (int[]) goodCopyOf(a,10); + System.out.println(Arrays.toString(a)); + + String[] str = {"a","b","c"}; + str = (String[]) goodCopyOf(str,10); + System.out.println(Arrays.toString(str)); + } + + public static Object goodCopyOf(Object a,int newLength){ + // 获取Class对象 + Class cl = a.getClass(); + // 如果不是数组对象,则返回null; + if (!cl.isArray()) return null; + // 获取数组组件对象 + Class componentType = cl.getComponentType(); + int length = Array.getLength(a); + Object newArray = Array.newInstance(componentType,newLength); + // 复制数组 + System.arraycopy(a,0,newArray,0,Math.min(length,newLength)); + return newArray; + } +} diff --git a/src/main/java/org/javacore/reflection/EmployeeClass.java b/src/main/java/org/javacore/reflection/EmployeeClass.java new file mode 100644 index 0000000..558bdde --- /dev/null +++ b/src/main/java/org/javacore/reflection/EmployeeClass.java @@ -0,0 +1,46 @@ +package org.javacore.reflection; + +/* + * Copyright [2015] [Jeff Lee] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @author Jeff Lee + * @since 2015年11月9日 10:45:19 + * 反射在继承中的案例 + */ +class Employee { + private String name; + public Employee(String name){ + this.name = name; + } + + public String getName(){ + return name; + } +} +class Manager extends Employee { + public Manager(String name) { + super(name); + } +} +public class EmployeeClass { + public static void main(String[] args) { + Employee employee = new Employee("Jeff"); + Employee manager = new Manager("Boss"); + System.out.println(employee.getClass().getName() + " " + employee.getName()); + System.out.println(manager.getClass().getName() + " " + manager.getName()); + } +} diff --git a/src/main/java/org/javacore/reflection/ObjectAnalyzer.java b/src/main/java/org/javacore/reflection/ObjectAnalyzer.java new file mode 100644 index 0000000..ee6beca --- /dev/null +++ b/src/main/java/org/javacore/reflection/ObjectAnalyzer.java @@ -0,0 +1,84 @@ +package org.javacore.reflection; + +import java.lang.reflect.AccessibleObject; +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; + +/* + * Copyright [2015] [Jeff Lee] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @author Jeff Lee + * @since 2015年11月9日 10:45:19 + * 反射对象分析工具 @{link test/org.javacore.reflection.ObjectAnalyzerTest} + */ +public class ObjectAnalyzer { + private ArrayList visited = new ArrayList(); + + public String toString(Object obj){ + if (obj == null) return "null"; + if (visited.contains(obj)) return "..."; + visited.add(obj); + + // 获取Class对象 + Class cl = obj.getClass(); + if (cl == String.class) return (String)obj; + // 如果对象是一个数组类 + if (cl.isArray()){ + // 获取数组组件 + String r = cl.getComponentType() + "[]{"; + for (int i = 0; i < Array.getLength(obj); i++) { + if (i> 0) r += ","; + Object val = Array.get(obj,i); + // 是否是一个基本类型 + if (cl.getComponentType().isPrimitive()) + r += val; + else r += toString(val); + } + return r + "}"; + } + + String r =cl.getName(); + do { + r += "["; + Field[] fields = cl.getDeclaredFields(); + AccessibleObject.setAccessible(fields,true); + for (Field f : fields){ + if (!Modifier.isStatic(f.getModifiers())){ + r += f.getName() + "="; + try { + Class t = f.getType(); + Object val = f.get(obj); + if (t.isPrimitive()) + r += val; + else + r +=toString(val); + } catch (Exception e){ + e.printStackTrace(); + } + } + } + r += "]"; + cl = cl.getSuperclass(); + } while (cl != null); + + return r; + } + + +} \ No newline at end of file diff --git a/src/main/java/org/javacore/reflection/ReflectionTest.java b/src/main/java/org/javacore/reflection/ReflectionTest.java new file mode 100644 index 0000000..b057cd9 --- /dev/null +++ b/src/main/java/org/javacore/reflection/ReflectionTest.java @@ -0,0 +1,127 @@ +package org.javacore.reflection; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +/* + * Copyright [2015] [Jeff Lee] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @author Jeff Lee + * @since 2015年11月9日 10:45:19 + * 反射对象构造函数、方法及字段 + */ +public class ReflectionTest { + public final int AGE = 1; + public static void main(String[] args) { + Class cl = null; + try { + cl = Class.forName("org.javacore.reflection.ReflectionTest"); + System.out.println("打印析构函数:"); + printConstructors(cl); + System.out.println("打印方法:"); + printMethods(cl); + System.out.println("打印字段:"); + printFields(cl); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + } + + /** + * 打印Class对象的析构方法 + * @param cl + */ + public static void printConstructors(Class cl){ + // 返回类所有的析构方法 + Constructor[] constructors = cl.getDeclaredConstructors(); + for (Constructor c : constructors){ + // 返回析构方法名称 + String name = c.getName(); + System.out.print(" "); + // 获取Java语言的修饰符 + // 修饰符由 Java 虚拟机的 public、protected、private、 + // final、static、abstract 和 interface 对应的常量组成; + String modifiers = Modifier.toString(c.getModifiers()); + if (modifiers.length()> 0) + System.out.print(modifiers + " "); + System.out.print(name + "("); + + // 获取析构方法的参数对象列表数组 + Class[] paramTypes = c.getParameterTypes(); + for (int i = 0; i < paramTypes.length;i++){ + if (i> 0) + System.out.print(", "); + System.out.print(paramTypes[i].getName()); + } + System.out.println(");"); + } + } + + /** + * 打印对象所有的方法 + * @param cl + */ + public static void printMethods(Class cl){ + // 获取类所有方法对象数组 + Method[] methods = cl.getMethods(); + for (Method m : methods) { + // 获取方法返回对象 + Class retType = m.getReturnType(); + String name = m.getName(); + + System.out.print(" "); + // 获取Java语言的修饰符 + // 修饰符由 Java 虚拟机的 public、protected、private、 + // final、static、abstract 和 interface 对应的常量组成; + String modifiers = Modifier.toString(cl.getModifiers()); + if (modifiers.length()> 0) + System.out.print(modifiers + " "); + System.out.print(retType.getName() +" " + name + "("); + + // 获取方法的参数对象列表数组 + Class[] paramTypes = m.getParameterTypes(); + for (int i = 0; i < paramTypes.length;i++){ + if (i> 0) + System.out.print(", "); + System.out.print(paramTypes[i].getName()); + } + System.out.println(");"); + } + } + + public static void printFields(Class clazz){ + // 获取字段Field对象数组 + Field[] fields = clazz.getFields(); + for (Field field : fields){ + // 获取字段声明类型对象 + Class type = field.getType(); + // 获取字段名称 + String name = field.getName(); + + System.out.print(" "); + // 获取Java语言的修饰符 + // 修饰符由 Java 虚拟机的 public、protected、private、 + // final、static、abstract 和 interface 对应的常量组成; + String modifiers = Modifier.toString(field.getModifiers()); + if (modifiers.length()> 0) + System.out.print(modifiers + " "); + System.out.print(type.getName() + " " + name); + } + } +} diff --git a/src/org/javacore/reflection/User.java b/src/main/java/org/javacore/reflection/User.java similarity index 100% rename from src/org/javacore/reflection/User.java rename to src/main/java/org/javacore/reflection/User.java diff --git a/src/org/javacore/reflection/UserConstructorReflect.java b/src/main/java/org/javacore/reflection/UserConstructorReflect.java similarity index 100% rename from src/org/javacore/reflection/UserConstructorReflect.java rename to src/main/java/org/javacore/reflection/UserConstructorReflect.java diff --git a/src/org/javacore/rtti/ClassInitialization.java b/src/main/java/org/javacore/rtti/ClassInitialization.java similarity index 100% rename from src/org/javacore/rtti/ClassInitialization.java rename to src/main/java/org/javacore/rtti/ClassInitialization.java diff --git a/src/org/javacore/rtti/ShowMethods.java b/src/main/java/org/javacore/rtti/ShowMethods.java similarity index 100% rename from src/org/javacore/rtti/ShowMethods.java rename to src/main/java/org/javacore/rtti/ShowMethods.java diff --git a/src/main/java/org/javacore/scheduler/SchedulerExecutorTest.java b/src/main/java/org/javacore/scheduler/SchedulerExecutorTest.java new file mode 100644 index 0000000..c6c4d0b --- /dev/null +++ b/src/main/java/org/javacore/scheduler/SchedulerExecutorTest.java @@ -0,0 +1,46 @@ +package org.javacore.scheduler; /* + * Copyright [2015] [Jeff Lee] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +/** + * ScheduledExecutorService的使用 + * @author BYSocket + * @since 2016年01月10日 14:20:00 + */ +public class SchedulerExecutorTest implements + Runnable { + private final String jobName; + + public SchedulerExecutorTest(String jobName) { + this.jobName = jobName; + } + + @Override + public void run() { + System.out.println("running => " + jobName); + } + + public static void main(String[] args) { + ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); + // 一秒 + executor.scheduleAtFixedRate(new SchedulerExecutorTest("job1"), 1, 1, TimeUnit.SECONDS); + // 两秒 + executor.scheduleWithFixedDelay(new SchedulerExecutorTest("job2"),1,2,TimeUnit.SECONDS); + } +} diff --git a/src/main/java/org/javacore/scheduler/SchedulerExecutorTest2.java b/src/main/java/org/javacore/scheduler/SchedulerExecutorTest2.java new file mode 100644 index 0000000..4b413ed --- /dev/null +++ b/src/main/java/org/javacore/scheduler/SchedulerExecutorTest2.java @@ -0,0 +1,116 @@ +package org.javacore.scheduler; /* + * Copyright [2015] [Jeff Lee] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.Calendar; +import java.util.Date; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +/** + * ScheduledExecutorService的使用 + * @author BYSocket + * @since 2016年01月10日 22:02:00 + */ +public class SchedulerExecutorTest2 implements Runnable{ + + private final String jobName; + + public SchedulerExecutorTest2(String jobName) { + this.jobName = jobName; + } + + @Override + public void run() { + System.out.println("Date = " + new Date() + ", running => " + jobName); + } + + /** + * 计算从当前时间currentDate开始,满足条件dayOfWeek, hourOfDay, + * minuteOfHour, secondOfMinite的最近时间 + * @return + */ + public Calendar getEarliestDate(Calendar currentDate, int dayOfWeek, + int hourOfDay, int minuteOfHour, int secondOfMinite) { + //计算当前时间的WEEK_OF_YEAR,DAY_OF_WEEK, HOUR_OF_DAY, MINUTE,SECOND等各个字段值 + int currentWeekOfYear = currentDate.get(Calendar.WEEK_OF_YEAR); + int currentDayOfWeek = currentDate.get(Calendar.DAY_OF_WEEK); + int currentHour = currentDate.get(Calendar.HOUR_OF_DAY); + int currentMinute = currentDate.get(Calendar.MINUTE); + int currentSecond = currentDate.get(Calendar.SECOND); + + //如果输入条件中的dayOfWeek小于当前日期的dayOfWeek,则WEEK_OF_YEAR需要推迟一周 + boolean weekLater = false; + if (dayOfWeek < currentDayOfWeek) { + weekLater = true; + } else if (dayOfWeek == currentDayOfWeek) { + //当输入条件与当前日期的dayOfWeek相等时,如果输入条件中的 + //hourOfDay小于当前日期的 + //currentHour,则WEEK_OF_YEAR需要推迟一周 + if (hourOfDay < currentHour) { + weekLater = true; + } else if (hourOfDay == currentHour) { + //当输入条件与当前日期的dayOfWeek, hourOfDay相等时, + //如果输入条件中的minuteOfHour小于当前日期的 + //currentMinute,则WEEK_OF_YEAR需要推迟一周 + if (minuteOfHour < currentMinute) { + weekLater = true; + } else if (minuteOfHour == currentSecond) { + //当输入条件与当前日期的dayOfWeek, hourOfDay, + //minuteOfHour相等时,如果输入条件中的 + //secondOfMinite小于当前日期的currentSecond, + //则WEEK_OF_YEAR需要推迟一周 + if (secondOfMinite < currentSecond) { + weekLater = true; + } + } + } + } + if (weekLater) { + //设置当前日期中的WEEK_OF_YEAR为当前周推迟一周 + currentDate.set(Calendar.WEEK_OF_YEAR, currentWeekOfYear + 1); + } + // 设置当前日期中的DAY_OF_WEEK,HOUR_OF_DAY,MINUTE,SECOND为输入条件中的值。 + currentDate.set(Calendar.DAY_OF_WEEK, dayOfWeek); + currentDate.set(Calendar.HOUR_OF_DAY, hourOfDay); + currentDate.set(Calendar.MINUTE, minuteOfHour); + currentDate.set(Calendar.SECOND, secondOfMinite); + return currentDate; + + } + + public static void main(String[] args) { + SchedulerExecutorTest2 executor = new SchedulerExecutorTest2("job1"); + // 获取当前时间 + Calendar currentDate = Calendar.getInstance(); + long currentDateLong = currentDate.getTime().getTime(); + System.out.println("Current Date = " + currentDate.getTime().toString()); + // 计算满足条件的最近一次执行时间 + Calendar earliestDate = executor.getEarliestDate(currentDate,3,16,38,10); + long earliestDateLong = earliestDate.getTime().getTime(); + System.out.println("Earliest Date = " + earliestDate.getTime().toString()); + // 计算从当前时间到最近一次执行时间的时间间隔 + long delay = earliestDateLong - currentDateLong; + // 计算执行周期为一星期 +// long period = 7 * 24 * 60 * 60 * 1000; + long period = 1000; + ScheduledExecutorService service = Executors.newScheduledThreadPool(10); + // 从现在开始delay毫秒之后,每隔一星期执行一次job1 + service.scheduleAtFixedRate(executor, delay, period, + TimeUnit.MILLISECONDS); + } + +} diff --git a/src/main/java/org/javacore/scheduler/TimerTest.java b/src/main/java/org/javacore/scheduler/TimerTest.java new file mode 100644 index 0000000..2253781 --- /dev/null +++ b/src/main/java/org/javacore/scheduler/TimerTest.java @@ -0,0 +1,45 @@ +package org.javacore.scheduler; +/* + * Copyright [2015] [Jeff Lee] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.Timer; +import java.util.TimerTask; + +/** + * Timer的使用 + * @author BYSocket + * @since 2016-01-09 22:19:00 + */ +public class TimerTest extends TimerTask{ + + private final String jobName; + + public TimerTest(String jobName) { + this.jobName = jobName; + } + + @Override + public void run() { + System.out.println("run the task => " + jobName); + } + + public static void main(String[] args) { + // 一种工具,线程用其安排以后在后台线程中执行的任务 + Timer timer = new Timer(); + timer.schedule(new TimerTest("Job 1") , 1000 , 1000); // 一秒 + timer.schedule(new TimerTest("Job 2") , 2000 , 2000); // 两秒 + } +} diff --git a/src/main/java/org/javacore/stream/CollectStreamTest.java b/src/main/java/org/javacore/stream/CollectStreamTest.java new file mode 100644 index 0000000..dcff4ae --- /dev/null +++ b/src/main/java/org/javacore/stream/CollectStreamTest.java @@ -0,0 +1,33 @@ +package org.javacore.stream; + +/* + * Copyright [2015] [Jeff Lee] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +/** + * + * Created by bysocket on 16/7/14. + */ +public class CollectStreamTest { + public static void main(String[] args) { + List list = Arrays.asList(1,2,3,4); + Double result = list.stream().collect(Collectors.averagingDouble(d->d*2)); + System.out.println(result); + } +} diff --git a/src/main/java/org/javacore/stream/CollectionStreamTest.java b/src/main/java/org/javacore/stream/CollectionStreamTest.java new file mode 100644 index 0000000..7d842a1 --- /dev/null +++ b/src/main/java/org/javacore/stream/CollectionStreamTest.java @@ -0,0 +1,79 @@ +package org.javacore.stream; + +/* + * Copyright [2015] [Jeff Lee] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * Stream API 集合的流式操作 + * + * Created by bysocket on 16/7/13. + */ +public class CollectionStreamTest { + public static void main(String[] args) { + List list = new ArrayList(); + list.add("aa"); + list.add("cccc"); + list.add("bbb"); + + /** + * Stream的使用: + * 创建/获取流 -> 中间操作(过滤、转换等) -> 终止操作( 聚合、收集结果) + */ + list.stream().forEach(System.out::println); + System.out.println(); + + /** + * 过滤 + * collect语法 {@link StreamCollectTest} + */ + List list0 = list.stream().filter(str -> str.startsWith("cc")).collect(Collectors.toList()); + List list1 = list.stream().filter(str -> str.startsWith("aa")).collect(Collectors.toList()); + + list0.stream().forEach(System.out::println); + list1.stream().forEach(System.out::println); + System.out.println(); + + /** + * 转换 + */ + List list2 = list.stream().map(str -> str.replace("c","*")).collect(Collectors.toList()); + + list2.stream().forEach(System.out::println); + System.out.println(); + + /** + * 提取 + * 从skip开始至limit位置为止 + */ + List list3 = list.stream().skip(0).limit(1).collect(Collectors.toList()); + + list3.stream().forEach(System.out::println); + System.out.println(); + + /** + * 组合 + */ + List list4 = Stream.concat(list.stream(),list.stream()).collect(Collectors.toList()); + + list4.stream().forEach(System.out::println); + System.out.println(); + } +} diff --git a/src/main/java/org/javacore/stream/CollectionStreamTest01.java b/src/main/java/org/javacore/stream/CollectionStreamTest01.java new file mode 100644 index 0000000..42a8499 --- /dev/null +++ b/src/main/java/org/javacore/stream/CollectionStreamTest01.java @@ -0,0 +1,38 @@ +package org.javacore.stream; + +/* + * Copyright [2015] [Jeff Lee] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.Arrays; +import java.util.List; + +/** + * Stream API 集合的流式操作 + *

+ * Created by bysocket on 16/7/13. + */ +public class CollectionStreamTest01 { + public static void main(String[] args) { + List strList = Arrays.asList("a1", "a2", "c3", "c6", "c4"); + + strList + .stream() + .filter(str -> str.startsWith("c")) + .map(String::toUpperCase) + .sorted() + .forEach(System.out::println); + } +} diff --git a/src/main/java/org/javacore/stream/ConcatStreamTest.java b/src/main/java/org/javacore/stream/ConcatStreamTest.java new file mode 100644 index 0000000..4ce98c1 --- /dev/null +++ b/src/main/java/org/javacore/stream/ConcatStreamTest.java @@ -0,0 +1,38 @@ +package org.javacore.stream; + +/* + * Copyright [2015] [Jeff Lee] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * 组合 - 流 + * + * Created by bysocket on 16/7/14. + */ +public class ConcatStreamTest { + public static void main(String[] args) { + List list1 = Arrays.asList("a","b","c"); + List list2 = Arrays.asList("d","e","f"); + + // 组合list1和list2的流 + List result = Stream.concat(list1.stream(),list2.stream()).collect(Collectors.toList()); + result.stream().forEach(System.out::println); + } +} diff --git a/src/main/java/org/javacore/stream/CountFilterStreamTest.java b/src/main/java/org/javacore/stream/CountFilterStreamTest.java new file mode 100644 index 0000000..8938156 --- /dev/null +++ b/src/main/java/org/javacore/stream/CountFilterStreamTest.java @@ -0,0 +1,43 @@ +package org.javacore.stream; + +/* + * Copyright [2015] [Jeff Lee] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +/** + * 过滤 + * 流的元素数量 + * + * Created by bysocket on 16/7/14. + */ +public class CountFilterStreamTest { + public static void main(String[] args) { + List list1 = Arrays.asList("a","b","ac"); + + // filter 过滤 + List result = list1.stream().filter(str -> str.startsWith("a")).collect(Collectors.toList()); + result.stream().forEach(System.out::println); + System.out.println(); + + // count 流的元素数量 + long l = list1.stream().filter(str -> str.startsWith("a")).count(); + System.out.println("list1 字符从a开始的数量:" + l); + + } +} diff --git a/src/main/java/org/javacore/stream/CreateStreamTest.java b/src/main/java/org/javacore/stream/CreateStreamTest.java new file mode 100644 index 0000000..5ee3111 --- /dev/null +++ b/src/main/java/org/javacore/stream/CreateStreamTest.java @@ -0,0 +1,27 @@ +package org.javacore.stream; + +/* + * Copyright [2015] [Jeff Lee] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * 创建流 + * + * Created by bysocket on 16/7/18. + */ +public class CreateStreamTest { + public static void main(String[] args) { + } +} diff --git a/src/main/java/org/javacore/stream/DistinctStreamTest.java b/src/main/java/org/javacore/stream/DistinctStreamTest.java new file mode 100644 index 0000000..639167e --- /dev/null +++ b/src/main/java/org/javacore/stream/DistinctStreamTest.java @@ -0,0 +1,36 @@ +package org.javacore.stream; + +/* + * Copyright [2015] [Jeff Lee] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +/** + * 去重 + * + * Created by bysocket on 16/7/14. + */ +public class DistinctStreamTest { + public static void main(String[] args) { + List list1 = Arrays.asList("a","b","b","b","ac"); + + // 去重 + List result = list1.stream().distinct().collect(Collectors.toList()); + result.stream().forEach(str -> System.out.print(str + " -> ")); + } +} diff --git a/src/main/java/org/javacore/stream/SortedStreamTest.java b/src/main/java/org/javacore/stream/SortedStreamTest.java new file mode 100644 index 0000000..1ffed70 --- /dev/null +++ b/src/main/java/org/javacore/stream/SortedStreamTest.java @@ -0,0 +1,33 @@ +package org.javacore.stream; + +/* + * Copyright [2015] [Jeff Lee] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.Arrays; +import java.util.List; + +/** + * 排序 + * + * Created by bysocket on 16/7/14. + */ +public class SortedStreamTest { + public static void main(String[] args) { + List list1 = Arrays.asList("a","e","b","ac"); + // 排序 + list1.stream().sorted().forEach(str -> System.out.print(str + " -> ")); + } +} diff --git a/src/org/javacore/thread/BasicThreads.java b/src/main/java/org/javacore/thread/BasicThreads.java similarity index 100% rename from src/org/javacore/thread/BasicThreads.java rename to src/main/java/org/javacore/thread/BasicThreads.java diff --git a/src/org/javacore/thread/CachedThreadPool.java b/src/main/java/org/javacore/thread/CachedThreadPool.java similarity index 100% rename from src/org/javacore/thread/CachedThreadPool.java rename to src/main/java/org/javacore/thread/CachedThreadPool.java diff --git a/src/org/javacore/thread/CallableDemo.java b/src/main/java/org/javacore/thread/CallableDemo.java similarity index 100% rename from src/org/javacore/thread/CallableDemo.java rename to src/main/java/org/javacore/thread/CallableDemo.java diff --git a/src/org/javacore/thread/DaemonFromFactory.java b/src/main/java/org/javacore/thread/DaemonFromFactory.java similarity index 100% rename from src/org/javacore/thread/DaemonFromFactory.java rename to src/main/java/org/javacore/thread/DaemonFromFactory.java diff --git a/src/org/javacore/thread/DaemonThreadFactory.java b/src/main/java/org/javacore/thread/DaemonThreadFactory.java similarity index 100% rename from src/org/javacore/thread/DaemonThreadFactory.java rename to src/main/java/org/javacore/thread/DaemonThreadFactory.java diff --git a/src/org/javacore/thread/DaemonsDontRunFinally.java b/src/main/java/org/javacore/thread/DaemonsDontRunFinally.java similarity index 100% rename from src/org/javacore/thread/DaemonsDontRunFinally.java rename to src/main/java/org/javacore/thread/DaemonsDontRunFinally.java diff --git a/src/org/javacore/thread/FixedThreadPool.java b/src/main/java/org/javacore/thread/FixedThreadPool.java similarity index 100% rename from src/org/javacore/thread/FixedThreadPool.java rename to src/main/java/org/javacore/thread/FixedThreadPool.java diff --git a/src/org/javacore/thread/LiftOff.java b/src/main/java/org/javacore/thread/LiftOff.java similarity index 100% rename from src/org/javacore/thread/LiftOff.java rename to src/main/java/org/javacore/thread/LiftOff.java diff --git a/src/org/javacore/thread/MoreBasicThreads.java b/src/main/java/org/javacore/thread/MoreBasicThreads.java similarity index 100% rename from src/org/javacore/thread/MoreBasicThreads.java rename to src/main/java/org/javacore/thread/MoreBasicThreads.java diff --git a/src/org/javacore/thread/MyRunnable.java b/src/main/java/org/javacore/thread/MyRunnable.java similarity index 100% rename from src/org/javacore/thread/MyRunnable.java rename to src/main/java/org/javacore/thread/MyRunnable.java diff --git a/src/org/javacore/thread/MyThread.java b/src/main/java/org/javacore/thread/MyThread.java similarity index 100% rename from src/org/javacore/thread/MyThread.java rename to src/main/java/org/javacore/thread/MyThread.java diff --git a/src/main/java/org/javacore/thread/ProcessBuilderTest.java b/src/main/java/org/javacore/thread/ProcessBuilderTest.java new file mode 100644 index 0000000..244da77 --- /dev/null +++ b/src/main/java/org/javacore/thread/ProcessBuilderTest.java @@ -0,0 +1,36 @@ +package org.javacore.thread; /* + * Copyright [2015] [Jeff Lee] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.Scanner; + +/** + * Java进程调用CMD + * VM options => -Dfile.encoding="GBK" + * @author BYSocket + * @since 2016年01月18日 16:08:00 + */ +public class ProcessBuilderTest { + public static void main(String[] args) throws IOException { + ProcessBuilder pb = new ProcessBuilder("cmd","/c","ipconfig/all"); + Process p = pb.start(); + + Scanner scanner = new Scanner(p.getInputStream()); + while (scanner.hasNext()) + System.out.println(scanner.next()); + scanner.close(); + } +} diff --git a/src/org/javacore/thread/SimpleDaemons.java b/src/main/java/org/javacore/thread/SimpleDaemons.java similarity index 100% rename from src/org/javacore/thread/SimpleDaemons.java rename to src/main/java/org/javacore/thread/SimpleDaemons.java diff --git a/src/org/javacore/thread/SimplePriorities.java b/src/main/java/org/javacore/thread/SimplePriorities.java similarity index 100% rename from src/org/javacore/thread/SimplePriorities.java rename to src/main/java/org/javacore/thread/SimplePriorities.java diff --git a/src/org/javacore/thread/SingleThreadExecutor.java b/src/main/java/org/javacore/thread/SingleThreadExecutor.java similarity index 100% rename from src/org/javacore/thread/SingleThreadExecutor.java rename to src/main/java/org/javacore/thread/SingleThreadExecutor.java diff --git a/src/main/java/org/javacore/thread/SleepRunThread.java b/src/main/java/org/javacore/thread/SleepRunThread.java new file mode 100644 index 0000000..8ee298b --- /dev/null +++ b/src/main/java/org/javacore/thread/SleepRunThread.java @@ -0,0 +1,43 @@ +package org.javacore.thread; /* + * Copyright [2015] [Jeff Lee] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Thread中start和run的区别 + * @author BYSocket + * @since 2016年01月18日 15:55:00 + */ +public class SleepRunThread { + public static void main(String[] args) { + System.out.println("当前线程ID => " + Thread.currentThread().getId()); + + SRThread t1 = new SRThread("t1"); + t1.start(); + SRThread t2 = new SRThread("t2"); + t2.run(); + } +} +class SRThread extends Thread { + private String name; + + public SRThread(String name) { + this.name = name; + } + + @Override + public void run() { + System.out.println("name:" + name +", 线程ID => " + Thread.currentThread().getId()); + } +} \ No newline at end of file diff --git a/src/org/javacore/thread/SleepingTask.java b/src/main/java/org/javacore/thread/SleepingTask.java similarity index 100% rename from src/org/javacore/thread/SleepingTask.java rename to src/main/java/org/javacore/thread/SleepingTask.java diff --git a/src/main/java/org/javacore/thread/ThreadInfo.java b/src/main/java/org/javacore/thread/ThreadInfo.java new file mode 100644 index 0000000..04edc13 --- /dev/null +++ b/src/main/java/org/javacore/thread/ThreadInfo.java @@ -0,0 +1,83 @@ +package org.javacore.thread; + + +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; + +/** + * 描述:线程优先级案例 + * Created by bysocket on 16/2/24. + */ +public class ThreadInfo { + public static void main(String[] args) { + Thread threads[] = new Thread[10]; + Thread.State status[] = new Thread.State[10]; + for (int i = 0; i < 10; i++) { + threads[i] = new Thread(new Calculator(i)); + if ((i % 2) == 0) { + threads[i].setPriority(Thread.MAX_PRIORITY); + } else { + threads[i].setPriority(Thread.MIN_PRIORITY); + } +// threads[i].setName(""); + } + + try { + // 将线程的信息写入log文件 + FileWriter fw = new FileWriter(".\\log.txt"); + PrintWriter pw = new PrintWriter(fw); + + for (int i = 0; i <10 ;i++) { + pw.println("Main: Status of Thread " + i + " : " + + threads[i].getState()); + status[i] = threads[i].getState(); + } + + // 启动线程 + for (int i = 0; i < 10 ;i++) + threads[i].start(); + + boolean finish = false; + while (!finish) { + for(int i = 0;i < 10 ;i++) { + if (threads[i].getState() != status[i]) { + writeThreadInfo(pw,threads[i],status[i]); + status[i] = threads[i].getState(); + } + } + finish = true; + for (int i = 0;i < 10 ;i++) { + finish = finish && (threads[i].getState() == Thread.State.TERMINATED);//中断 + } + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + private static void writeThreadInfo(PrintWriter pw, Thread thread, Thread.State status) { + pw.printf("Main: Id %d - $s\n",thread.getId(),thread.getName()); + pw.printf("Main: Priority: %d\n",thread.getPriority()); + pw.printf("Main: OldState: %s\n",status); + pw.printf("Main: New State: %s\n",thread.getState()); + pw.printf("*****************************************\n"); + } +} +class Calculator implements Runnable { + + private int number; + + public Calculator(int number) { + this.number = number; + } + + @Override + public void run() { + for (int i = 0;i <=10; i++) { + System.out.printf("%s: %d * %d = %d\n", + Thread.currentThread().getName(), + number, i, i * number); + } + } +} diff --git a/src/main/java/org/javacore/thread/ThreadInterrupt.java b/src/main/java/org/javacore/thread/ThreadInterrupt.java new file mode 100644 index 0000000..3d7009d --- /dev/null +++ b/src/main/java/org/javacore/thread/ThreadInterrupt.java @@ -0,0 +1,22 @@ +package org.javacore.thread; + +/** + * Created by bysocket on 16/2/24. + */ +public class ThreadInterrupt { + public static void main(String[] args) throws InterruptedException { + Thread inThread = new Thread(new InterrupThread()); + inThread.start(); + Thread.sleep(1000); + inThread.interrupt(); + } +} +class InterrupThread implements Runnable { + + private int num = 1; + @Override + public void run() { + while (true) + System.out.println("true ----> " + num++); + } +} diff --git a/src/main/java/org/javacore/thread/daemon/CleanerTask.java b/src/main/java/org/javacore/thread/daemon/CleanerTask.java new file mode 100644 index 0000000..eba932c --- /dev/null +++ b/src/main/java/org/javacore/thread/daemon/CleanerTask.java @@ -0,0 +1,52 @@ +package org.javacore.thread.daemon; + +import java.util.Date; +import java.util.Deque; + +/** + * 描述:管理这个队列,如果事件超过10秒钟,就会被移除 + * Created by bysocket on 16/3/4. + */ +public class CleanerTask extends Thread{ + private Deque deque; + + public CleanerTask(Deque deque) { + this.deque = deque; + setDaemon(true); + } + + @Override + public void run() { + while (true) { + Date date = new Date(); + clean(date); + } + } + + /** + * 删除该时间前10s内创建的事件对象 + * @param date + */ + private void clean(Date date) { + long difference = 0; + boolean delete; + if (deque.size() == 0) { + return; + } + delete = false; + + do { + Event e = deque.getLast(); + difference = date.getTime() - e.getDate().getTime(); + if (difference> 10000) { + System.out.printf("Cleaner: %s \n",e.getEvent()); + deque.removeLast(); + delete = true; + } + } while (difference> 10000); + + if (delete) { + System.out.printf("Cleaner: Size of the queue: %d\n",deque.size()); + } + } +} diff --git a/src/main/java/org/javacore/thread/daemon/DaemonTest.java b/src/main/java/org/javacore/thread/daemon/DaemonTest.java new file mode 100644 index 0000000..3758870 --- /dev/null +++ b/src/main/java/org/javacore/thread/daemon/DaemonTest.java @@ -0,0 +1,23 @@ +package org.javacore.thread.daemon; + +import java.util.ArrayDeque; +import java.util.Deque; + +/** + * 1. 知道3个WriteTask线程休眠后,CleanerTask才执行 + * 2. 从结果中,可以看出队列维持在一定数量当中 + * Created by bysocket on 16/3/4. + */ +public class DaemonTest { + public static void main(String[] args) { + Deque deque = new ArrayDeque(); + WriterTask writerTask = new WriterTask(deque); + for (int i = 0; i < 3 ; i++) { + Thread thread = new Thread(writerTask); + thread.start(); + } + + CleanerTask cleanerTask = new CleanerTask(deque); + cleanerTask.start(); + } +} diff --git a/src/main/java/org/javacore/thread/daemon/Event.java b/src/main/java/org/javacore/thread/daemon/Event.java new file mode 100644 index 0000000..3030ccb --- /dev/null +++ b/src/main/java/org/javacore/thread/daemon/Event.java @@ -0,0 +1,28 @@ +package org.javacore.thread.daemon; + +import java.util.Date; + +/** + * 描述:事件类 + * Created by bysocket on 16/3/4. + */ +public class Event { + private Date date; + private String event; + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public String getEvent() { + return event; + } + + public void setEvent(String event) { + this.event = event; + } +} diff --git a/src/main/java/org/javacore/thread/daemon/WriterTask.java b/src/main/java/org/javacore/thread/daemon/WriterTask.java new file mode 100644 index 0000000..70e3e5f --- /dev/null +++ b/src/main/java/org/javacore/thread/daemon/WriterTask.java @@ -0,0 +1,33 @@ +package org.javacore.thread.daemon; + +import java.util.Date; +import java.util.Deque; +import java.util.concurrent.TimeUnit; + +/** + * 描述:写事件到一个队列 + * Created by bysocket on 16/3/4. + */ +public class WriterTask implements Runnable { + private Deque deque; + + public WriterTask(Deque deque) { + this.deque = deque; + } + + @Override + public void run() { + for (int i = 1; i < 100; i++) { + Event event = new Event(); + event.setDate(new Date()); + event.setEvent(String.format("The thread %s has generated an event",Thread.currentThread().getId())); + deque.addFirst(event); + + try { + TimeUnit.SECONDS.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } +} diff --git a/src/main/java/org/javacore/thread/join/DSLoader.java b/src/main/java/org/javacore/thread/join/DSLoader.java new file mode 100644 index 0000000..07e8019 --- /dev/null +++ b/src/main/java/org/javacore/thread/join/DSLoader.java @@ -0,0 +1,19 @@ +package org.javacore.thread.join; + +import java.util.concurrent.TimeUnit; + +/** + * Created by bysocket on 16/3/3. + */ +public class DSLoader implements Runnable { + @Override + public void run() { + System.out.println("begining the DSLoader"); + try { + TimeUnit.SECONDS.sleep(4); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("DSLoader has finished"); + } +} diff --git a/src/main/java/org/javacore/thread/join/JoinTest.java b/src/main/java/org/javacore/thread/join/JoinTest.java new file mode 100644 index 0000000..d0ed248 --- /dev/null +++ b/src/main/java/org/javacore/thread/join/JoinTest.java @@ -0,0 +1,20 @@ +package org.javacore.thread.join; + +/** + * Created by bysocket on 16/3/3. + */ +public class JoinTest { + public static void main(String[] args) throws InterruptedException { + Thread t1 = new Thread(new DSLoader()); + Thread t2 = new Thread(new NetLoader()); + + t1.start(); + t2.start(); + + //可以注释其中一个加深理解 + t1.join(); + //t2.join(); + + System.out.println("ending all"); + } +} diff --git a/src/main/java/org/javacore/thread/join/NetLoader.java b/src/main/java/org/javacore/thread/join/NetLoader.java new file mode 100644 index 0000000..951b214 --- /dev/null +++ b/src/main/java/org/javacore/thread/join/NetLoader.java @@ -0,0 +1,19 @@ +package org.javacore.thread.join; + +import java.util.concurrent.TimeUnit; + +/** + * Created by bysocket on 16/3/3. + */ +public class NetLoader implements Runnable { + @Override + public void run() { + System.out.println("begining the NetLoader"); + try { + TimeUnit.SECONDS.sleep(6); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("NetLoader has finished"); + } +} diff --git a/src/main/java/org/javacore/thread/threadlocal/SafeTask.java b/src/main/java/org/javacore/thread/threadlocal/SafeTask.java new file mode 100644 index 0000000..3037ad8 --- /dev/null +++ b/src/main/java/org/javacore/thread/threadlocal/SafeTask.java @@ -0,0 +1,36 @@ +package org.javacore.thread.threadlocal; + +import java.util.Date; +import java.util.concurrent.TimeUnit; + +/** + * 描述:看类里面说明 + * Created by bysocket on 16/3/8. + */ +public class SafeTask implements Runnable{ + /** + * ThreadLocal对象不会被所有线程共享 + * --> 线程局部变量 <-- + */ + private static ThreadLocal startDate = new ThreadLocal(){ + /** + * 隐式实现初始化对象 + * @return + */ + @Override + protected Date initialValue() { + return new Date(); + } + }; + + @Override + public void run() { + System.out.printf("Starting Thread:%s : %s\n",Thread.currentThread().getId(),startDate.get()); + try { + TimeUnit.SECONDS.sleep((int) Math.rint(Math.random() * 10)); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.printf("Finish Thread:%s : %s\n",Thread.currentThread().getId(),startDate.get()); + } +} diff --git a/src/main/java/org/javacore/thread/threadlocal/SafeTest.java b/src/main/java/org/javacore/thread/threadlocal/SafeTest.java new file mode 100644 index 0000000..0202b0e --- /dev/null +++ b/src/main/java/org/javacore/thread/threadlocal/SafeTest.java @@ -0,0 +1,23 @@ +package org.javacore.thread.threadlocal; + +import java.util.concurrent.TimeUnit; + +/** + * 描述:可以看到线程每个有不同的启动时间,但是结束时间也会不相同. + * Created by bysocket on 16/3/8. + */ +public class SafeTest { + public static void main(String[] args) { + SafeTask task = new SafeTask(); + for (int i = 0 ; i < 10; i++) { + Thread thread = new Thread(task); + thread.start(); + + try { + TimeUnit.SECONDS.sleep(2); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } +} diff --git a/src/main/java/org/javacore/thread/threadlocal/UnsafeTask.java b/src/main/java/org/javacore/thread/threadlocal/UnsafeTask.java new file mode 100644 index 0000000..2aed77d --- /dev/null +++ b/src/main/java/org/javacore/thread/threadlocal/UnsafeTask.java @@ -0,0 +1,24 @@ +package org.javacore.thread.threadlocal; + +import java.util.Date; +import java.util.concurrent.TimeUnit; + +/** + * 描述:私有变量会被所有线程共享 + * Created by bysocket on 16/3/8. + */ +public class UnsafeTask implements Runnable{ + private Date startDate; + + @Override + public void run() { + startDate = new Date(); + System.out.printf("Starting Thread:%s : %s\n",Thread.currentThread().getId(),startDate); + try { + TimeUnit.SECONDS.sleep((int) Math.rint(Math.random() * 10)); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.printf("Finish Thread:%s : %s\n",Thread.currentThread().getId(),startDate); + } +} diff --git a/src/main/java/org/javacore/thread/threadlocal/UnsafeTest.java b/src/main/java/org/javacore/thread/threadlocal/UnsafeTest.java new file mode 100644 index 0000000..0bb44f9 --- /dev/null +++ b/src/main/java/org/javacore/thread/threadlocal/UnsafeTest.java @@ -0,0 +1,23 @@ +package org.javacore.thread.threadlocal; + +import java.util.concurrent.TimeUnit; + +/** + * 描述:可以看到线程每个有不同的启动时间,但是结束时间会有相同. + * Created by bysocket on 16/3/8. + */ +public class UnsafeTest { + public static void main(String[] args) { + UnsafeTask task = new UnsafeTask(); + for (int i = 0 ; i < 10; i++) { + Thread thread = new Thread(task); + thread.start(); + + try { + TimeUnit.SECONDS.sleep(2); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } +} diff --git a/src/main/java/org/javacore/thread/uncaughtexp/ExceptionHadler.java b/src/main/java/org/javacore/thread/uncaughtexp/ExceptionHadler.java new file mode 100644 index 0000000..a60c42c --- /dev/null +++ b/src/main/java/org/javacore/thread/uncaughtexp/ExceptionHadler.java @@ -0,0 +1,19 @@ +package org.javacore.thread.uncaughtexp; + +import java.lang.Thread.UncaughtExceptionHandler; + +/** + * 描述:处理运行时异常的类 + * Created by bysocket on 16/3/4. + */ +public class ExceptionHadler implements UncaughtExceptionHandler{ + @Override + public void uncaughtException(Thread t, Throwable e) { + System.out.printf("An exception has been captured\n"); + System.out.printf("Thread: %s\n",t.getId()); + System.out.printf("Exception: %s: %s\n",e.getClass().getName(),e.getMessage()); + System.out.printf("Stack Trace: \n"); + e.printStackTrace(System.out); + System.out.printf("Thread status: %s\n",t.getState()); + } +} diff --git a/src/main/java/org/javacore/thread/uncaughtexp/UncaughtTask.java b/src/main/java/org/javacore/thread/uncaughtexp/UncaughtTask.java new file mode 100644 index 0000000..696a822 --- /dev/null +++ b/src/main/java/org/javacore/thread/uncaughtexp/UncaughtTask.java @@ -0,0 +1,12 @@ +package org.javacore.thread.uncaughtexp; + +/** + * 描述:抛出运行时异常的线程类 + * Created by bysocket on 16/3/4. + */ +public class UncaughtTask implements Runnable { + @Override + public void run() { + int numero = Integer.parseInt("TTTT"); + } +} diff --git a/src/main/java/org/javacore/thread/uncaughtexp/UncaughtTest.java b/src/main/java/org/javacore/thread/uncaughtexp/UncaughtTest.java new file mode 100644 index 0000000..059f074 --- /dev/null +++ b/src/main/java/org/javacore/thread/uncaughtexp/UncaughtTest.java @@ -0,0 +1,14 @@ +package org.javacore.thread.uncaughtexp; + +/** + * 描述:实现异常类Test + * Created by bysocket on 16/3/4. + */ +public class UncaughtTest { + public static void main(String[] args) { + UncaughtTask uncaughtTask = new UncaughtTask(); + Thread thread = new Thread(uncaughtTask); + thread.setUncaughtExceptionHandler(new ExceptionHadler()); + thread.start(); + } +} diff --git a/src/main/java/org/javacore/time/Duration.java b/src/main/java/org/javacore/time/Duration.java new file mode 100644 index 0000000..9d23c31 --- /dev/null +++ b/src/main/java/org/javacore/time/Duration.java @@ -0,0 +1,319 @@ +package org.javacore.time; + +import com.google.common.base.Preconditions; +import com.google.common.collect.Maps; + +import java.io.Serializable; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Title: Duration + * Create Date: 2016-08-26 15:43 + * Description: Duration unit, consisting of length and time unit. + * Simple time convert. + * + * @author Yufan + */ +public class Duration implements Serializable { + private static final long serialVersionUID = 3898309763927286550L; + + /** + * A duration of Long.MAX_VALUE Days + */ + public static final Duration INFINITE = new Duration(); + + /** + * Common time pattern + */ + private static final Pattern PATTERN = Pattern.compile( + "(∞|inf|infinite)|" + "(([\\d]+)[\\s]*(" + "ns|nanosecond(s)?|" + "us|microsecond(s)?|" + "ms|millisecond(s)?|" + "s|second(s)?|" + + "m|min|mins|minute(s)?|" + "h|hour(s)?|" + "d|day(s)?" + "))"); + private static final Map SUFFIXES; + + public final long length; + public final TimeUnit timeUnit; + public final boolean finite; + + static { + SUFFIXES = Maps.newHashMapWithExpectedSize(32); + + SUFFIXES.put("ns", TimeUnit.NANOSECONDS); + SUFFIXES.put("nanosecond", TimeUnit.NANOSECONDS); + SUFFIXES.put("nanoseconds", TimeUnit.NANOSECONDS); + + SUFFIXES.put("us", TimeUnit.MICROSECONDS); + SUFFIXES.put("microsecond", TimeUnit.MICROSECONDS); + SUFFIXES.put("microseconds", TimeUnit.MICROSECONDS); + + SUFFIXES.put("ms", TimeUnit.MILLISECONDS); + SUFFIXES.put("millisecond", TimeUnit.MILLISECONDS); + SUFFIXES.put("milliseconds", TimeUnit.MILLISECONDS); + + SUFFIXES.put("s", TimeUnit.SECONDS); + SUFFIXES.put("second", TimeUnit.SECONDS); + SUFFIXES.put("seconds", TimeUnit.SECONDS); + + SUFFIXES.put("m", TimeUnit.MINUTES); + SUFFIXES.put("min", TimeUnit.MINUTES); + SUFFIXES.put("mins", TimeUnit.MINUTES); + SUFFIXES.put("minute", TimeUnit.MINUTES); + SUFFIXES.put("minutes", TimeUnit.MINUTES); + + SUFFIXES.put("h", TimeUnit.HOURS); + SUFFIXES.put("hour", TimeUnit.HOURS); + SUFFIXES.put("hours", TimeUnit.HOURS); + + SUFFIXES.put("d", TimeUnit.DAYS); + SUFFIXES.put("day", TimeUnit.DAYS); + SUFFIXES.put("days", TimeUnit.DAYS); + } + + /** + * Infinite constructor. + */ + private Duration() { + finite = false; + this.length = Long.MAX_VALUE; + this.timeUnit = TimeUnit.DAYS; + } + + private Duration(long length, TimeUnit timeUnit) { + this.length = length; + this.timeUnit = Preconditions.checkNotNull(timeUnit, "timeUnit"); + finite = !(length == Long.MAX_VALUE && TimeUnit.DAYS.equals(timeUnit)); + } + + /** + * Returns the Duration converted to days. + */ + public long toDays() { + return TimeUnit.DAYS.convert(length, timeUnit); + } + + /** + * Returns the Duration converted to hours. + */ + public long toHours() { + return TimeUnit.HOURS.convert(length, timeUnit); + } + + /** + * Returns the Duration converted to microseconds. + */ + public long toMicros() { + return TimeUnit.MICROSECONDS.convert(length, timeUnit); + } + + /** + * Returns the Duration converted to microseconds. + */ + public long toMicroseconds() { + return TimeUnit.MICROSECONDS.convert(length, timeUnit); + } + + /** + * Returns the Duration converted to milliseconds. + */ + public long toMillis() { + return TimeUnit.MILLISECONDS.convert(length, timeUnit); + } + + /** + * Returns the Duration converted to milliseconds. + */ + public long toMilliseconds() { + return TimeUnit.MILLISECONDS.convert(length, timeUnit); + } + + /** + * Returns the Duration converted to minutes. + */ + public long toMins() { + return TimeUnit.MINUTES.convert(length, timeUnit); + } + + /** + * Returns the Duration converted to minutes. + */ + public long toMinutes() { + return TimeUnit.MINUTES.convert(length, timeUnit); + } + + /** + * Returns the Duration converted to nanoseconds. + */ + public long toNanos() { + return TimeUnit.NANOSECONDS.convert(length, timeUnit); + } + + /** + * Returns the Duration converted to nanoseconds. + */ + public long toNanoseconds() { + return TimeUnit.NANOSECONDS.convert(length, timeUnit); + } + + /** + * Returns the Duration converted to seconds. + */ + public long toSeconds() { + return TimeUnit.SECONDS.convert(length, timeUnit); + } + + /** + * Returns the Duration converted to seconds. + */ + public long toSecs() { + return TimeUnit.SECONDS.convert(length, timeUnit); + } + + /** + * Returns a Duration of {@code count} days. + */ + public static Duration days(long count) { + return new Duration(count, TimeUnit.DAYS); + } + + /** + * Returns a Duration of {@code count} hours. + */ + public static Duration hours(long count) { + return new Duration(count, TimeUnit.HOURS); + } + + /** + * Returns an infinite duration of Long.MAX_VALUE days. + */ + public static Duration inf() { + return INFINITE; + } + + /** + * Returns an infinite duration of Long.MAX_VALUE days. + */ + public static Duration infinite() { // NOSONAR + return INFINITE; + } + + /** + * Returns a Duration of {@code count} microseconds. + */ + public static Duration microseconds(long count) { + return new Duration(count, TimeUnit.MICROSECONDS); + } + + /** + * Returns a Duration of {@code count} milliseconds. + */ + public static Duration millis(long count) { + return new Duration(count, TimeUnit.MILLISECONDS); + } + + /** + * Returns a Duration of {@code count} milliseconds. + */ + public static Duration milliseconds(long count) { + return new Duration(count, TimeUnit.MILLISECONDS); + } + + /** + * Returns a Duration of {@code count} minutes. + */ + public static Duration mins(long count) { + return new Duration(count, TimeUnit.MINUTES); + } + + /** + * Returns a Duration of {@code count} minutes. + */ + public static Duration minutes(long count) { + return new Duration(count, TimeUnit.MINUTES); + } + + /** + * Returns a Duration of {@code count} nanoseconds. + */ + public static Duration nanos(long count) { + return new Duration(count, TimeUnit.NANOSECONDS); + } + + /** + * Returns a Duration of {@code count} nanoseconds. + */ + public static Duration nanoseconds(long count) { + return new Duration(count, TimeUnit.NANOSECONDS); + } + + /** + * Returns a Duration of {@code count} {@code unit}s. + */ + public static Duration of(long count, TimeUnit unit) { + return new Duration(count, unit); + } + + /** + * Returns a Duration from the parsed {@code duration}. Example: + *
+ *

+ * 5 s
+ * 5 seconds
+ * 10m
+ * 10 minutes
+ * 
+ */ + public static Duration of(String duration) { + Matcher matcher = PATTERN.matcher(duration); + if (!matcher.matches()) { + throw new IllegalArgumentException("Invalid duration: " + duration); + } + + if (matcher.group(1) != null) { + return INFINITE; + } else { + String unit = matcher.group(4); + String value = matcher.group(3); + return new Duration(Long.parseLong(value), SUFFIXES.get(unit)); + } + } + + /** + * Returns a Duration of {@code count} seconds. + */ + public static Duration seconds(long count) { + return new Duration(count, TimeUnit.SECONDS); + } + + /** + * Returns a Duration of {@code count} seconds. + */ + public static Duration secs(long count) { + return new Duration(count, TimeUnit.SECONDS); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if ((obj == null) || (getClass() != obj.getClass())) { + return false; + } + final Duration duration = (Duration) obj; + return (length == duration.length) && (timeUnit == duration.timeUnit); + } + + @Override + public int hashCode() { + return (31 * (int) (length ^ (length>>> 32))) + timeUnit.hashCode(); + } + + @Override + public String toString() { + String units = timeUnit.toString().toLowerCase(); + if (length == 1) + units = units.substring(0, units.length() - 1); + return Long.toString(length) + ' ' + units; + } +} diff --git a/src/main/java/org/javacore/time/TimeUtil.java b/src/main/java/org/javacore/time/TimeUtil.java new file mode 100644 index 0000000..34d0011 --- /dev/null +++ b/src/main/java/org/javacore/time/TimeUtil.java @@ -0,0 +1,118 @@ +package org.javacore.time; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +/** + * 基于 JDK 8 time包的时间工具类 + *

+ * Created by bysocket on 16/8/23. + */ +public final class TimeUtil { + + /** + * 获取默认时间格式: yyyy-MM-dd HH:mm:ss + */ + private static final DateTimeFormatter DEFAULT_DATETIME_FORMATTER = TimeFormat.LONG_DATE_PATTERN_LINE.formatter; + + private TimeUtil() { + // no construct function + } + + /** + * String 转时间 + * + * @param timeStr + * @return + */ + public static LocalDateTime parseTime(String timeStr) { + return LocalDateTime.parse(timeStr, DEFAULT_DATETIME_FORMATTER); + } + + /** + * String 转时间 + * + * @param timeStr + * @param format 时间格式 + * @return + */ + public static LocalDateTime parseTime(String timeStr, TimeFormat format) { + return LocalDateTime.parse(timeStr, format.formatter); + } + + /** + * 时间转 String + * + * @param time + * @return + */ + public static String parseTime(LocalDateTime time) { + return DEFAULT_DATETIME_FORMATTER.format(time); + } + + /** + * 时间转 String + * + * @param time + * @param format 时间格式 + * @return + */ + public static String parseTime(LocalDateTime time, TimeFormat format) { + return format.formatter.format(time); + } + + /** + * 获取当前时间 + * + * @return + */ + public static String getCurrentDatetime() { + return DEFAULT_DATETIME_FORMATTER.format(LocalDateTime.now()); + } + + /** + * 获取当前时间 + * + * @param format 时间格式 + * @return + */ + public static String getCurrentDatetime(TimeFormat format) { + return format.formatter.format(LocalDateTime.now()); + } + + /** + * 时间格式 + */ + public enum TimeFormat { + + /** + * 短时间格式 + */ + SHORT_DATE_PATTERN_LINE("yyyy-MM-dd"), + SHORT_DATE_PATTERN_SLASH("yyyy/MM/dd"), + SHORT_DATE_PATTERN_DOUBLE_SLASH("yyyy\\MM\\dd"), + SHORT_DATE_PATTERN_NONE("yyyyMMdd"), + + /** + * 长时间格式 + */ + LONG_DATE_PATTERN_LINE("yyyy-MM-dd HH:mm:ss"), + LONG_DATE_PATTERN_SLASH("yyyy/MM/dd HH:mm:ss"), + LONG_DATE_PATTERN_DOUBLE_SLASH("yyyy\\MM\\dd HH:mm:ss"), + LONG_DATE_PATTERN_NONE("yyyyMMdd HH:mm:ss"), + + /** + * 长时间格式 带毫秒 + */ + LONG_DATE_PATTERN_WITH_MILSEC_LINE("yyyy-MM-dd HH:mm:ss.SSS"), + LONG_DATE_PATTERN_WITH_MILSEC_SLASH("yyyy/MM/dd HH:mm:ss.SSS"), + LONG_DATE_PATTERN_WITH_MILSEC_DOUBLE_SLASH("yyyy\\MM\\dd HH:mm:ss.SSS"), + LONG_DATE_PATTERN_WITH_MILSEC_NONE("yyyyMMdd HH:mm:ss.SSS"); + + private transient DateTimeFormatter formatter; + + TimeFormat(String pattern) { + formatter = DateTimeFormatter.ofPattern(pattern); + } + } +} diff --git a/src/main/java/org/jee/rpc/EchoService.java b/src/main/java/org/jee/rpc/EchoService.java new file mode 100644 index 0000000..e329980 --- /dev/null +++ b/src/main/java/org/jee/rpc/EchoService.java @@ -0,0 +1,9 @@ +package org.jee.rpc; + +/** + * 描述:服务Echo接口类 + * Created by bysocket on 16/2/28. + */ +public interface EchoService { + String echo(String ping); +} diff --git a/src/main/java/org/jee/rpc/EchoServiceImpl.java b/src/main/java/org/jee/rpc/EchoServiceImpl.java new file mode 100644 index 0000000..0403ea9 --- /dev/null +++ b/src/main/java/org/jee/rpc/EchoServiceImpl.java @@ -0,0 +1,12 @@ +package org.jee.rpc; + +/** + * 描述:服务Echo实现类 + * Created by bysocket on 16/2/28. + */ +public class EchoServiceImpl implements EchoService { + @Override + public String echo(String ping) { + return ping != null ? ping + " --> I am ok." : "I am ok."; + } +} diff --git a/src/main/java/org/jee/rpc/RpcExporter.java b/src/main/java/org/jee/rpc/RpcExporter.java new file mode 100644 index 0000000..567e187 --- /dev/null +++ b/src/main/java/org/jee/rpc/RpcExporter.java @@ -0,0 +1,107 @@ +package org.jee.rpc; + +import java.io.IOException; +import java.io.ObjectInput; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.lang.reflect.Method; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; + +/** + * 描述:RPC服务发布者 + * Created by bysocket on 16/2/28. + */ +public class RpcExporter { + // 创建线程池 + static Executor executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); + + public static void exporter(String hostName,int port) throws IOException { + ServerSocket serverSocket = new ServerSocket(); + serverSocket.bind(new InetSocketAddress(hostName,port)); + try { + while (true) { + /** + * 监听Client的TCP连接,将其封装成Task,由线程池执行. + */ + executor.execute(new ExporterTask(serverSocket.accept())); + } + } finally { + serverSocket.close(); + } + } + + /** + * 线程Task: + * 1. 将客户端发送的二进制流反序列化成对象,反射调用服务实现者,获取执行结果 + * 2. 将执行结果对象反序列化,通过Socket发送给客户端 + * 3. 远程服务调用完成之后,释放Socket等连接资源,防止句柄泄漏 + */ + private static class ExporterTask implements Runnable { + Socket client = null; + public ExporterTask(Socket accept) { + this.client = accept; + } + + @Override + public void run() { + ObjectInputStream input = null; + ObjectOutputStream output = null; + try { + // 对象输入流 + input = new ObjectInputStream(client.getInputStream()); + + // 获取接口名 + String interfaceName = input.readUTF(); + // 获取方法名 + String methodName = input.readUTF(); + // 获取方法的参数数组 + Class[] paramTypes = (Class[]) input.readObject(); + // 获取传入参数对象数组 + Object[] arguments = (Object[]) input.readObject(); + + // 获取服务对象类 + Class service = Class.forName(interfaceName); + // 获取服务方法 + Method method = service.getMethod(methodName,paramTypes); + // 获取服务方法返回对象 + Object result = method.invoke(service.newInstance(),arguments); + + // 对象输出流 + output = new ObjectOutputStream(client.getOutputStream()); + output.writeObject(result); + + } catch (Exception e) { + e.printStackTrace(); + } finally { + // 关闭流的操作 + if (output != null) { + try { + output.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + if (input != null) { + try { + input.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + if (client != null) { + try { + client.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + } +} diff --git a/src/main/java/org/jee/rpc/RpcImporter.java b/src/main/java/org/jee/rpc/RpcImporter.java new file mode 100644 index 0000000..c4359fc --- /dev/null +++ b/src/main/java/org/jee/rpc/RpcImporter.java @@ -0,0 +1,60 @@ +package org.jee.rpc; + +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.net.InetSocketAddress; +import java.net.Socket; + +/** + * 描述:Rpc本地服务代理类 + * 1. 将本地接口调用转化为JDK的动态调用,在动态调用中实现接口的远程调用 + * 2. 创建Socket客户端,根据制定地址连接远程服务提供者 + * 3. 将远程服务调用所需的接口类,方法名,参数列表等编码后发送给服务提供者 + * 4. 同步阻塞等待服务端返回应答,获取应答后返回 + * Created by bysocket on 16/2/29. + */ +public class RpcImporter { + public S importer(final Class serviceClass, final InetSocketAddress address) { + // JDK动态代理,实现接口的远程调用 + return (S) Proxy.newProxyInstance(serviceClass.getClassLoader(), + new Class[]{serviceClass.getInterfaces()[0]}, + new InvocationHandler() { + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + Socket socket = null; + ObjectOutputStream output = null; + ObjectInputStream input = null; + + try { + // 连接远程服务提供者 + socket = new Socket(); + socket.connect(address); + + // 对象输出流 + output = new ObjectOutputStream(socket.getOutputStream()); + output.writeUTF(serviceClass.getName()); + output.writeUTF(method.getName()); + output.writeObject(method.getParameterTypes()); + output.writeObject(args); + + input = new ObjectInputStream(socket.getInputStream()); + return input.readObject(); + } finally { + if (socket != null) { + socket.close(); + } + if (output != null) { + output.close(); + } + if (input != null) { + input.close(); + } + } + } + }); + } +} diff --git a/src/main/java/org/jee/rpc/RpcTest.java b/src/main/java/org/jee/rpc/RpcTest.java new file mode 100644 index 0000000..07fef5b --- /dev/null +++ b/src/main/java/org/jee/rpc/RpcTest.java @@ -0,0 +1,31 @@ +package org.jee.rpc; + +import java.io.IOException; +import java.net.InetSocketAddress; + +/** + * 描述:RPC测试代码类 + * Created by bysocket on 16/2/29. + */ +public class RpcTest { + public static void main(String[] args) { + // 启动服务提供者 + new Thread(new Runnable() { + @Override + public void run() { + try { + RpcExporter.exporter("localhost",8088); + } catch (IOException e) { + e.printStackTrace(); + } + } + }).start(); + + // 创建服务本地代理 + RpcImporter importer = new RpcImporter(); + + // 从服务本地代理获取服务对象类 + EchoService echo = importer.importer(EchoServiceImpl.class,new InetSocketAddress("localhost",8088)); + System.out.println(echo.echo("Are you OK?")); + } +} diff --git "a/src/resources/collections/347円273円230円345円233円2761円.vsdx" "b/src/main/resources/collections/347円273円230円345円233円2761円.vsdx" similarity index 100% rename from "src/resources/collections/347円273円230円345円233円2761円.vsdx" rename to "src/main/resources/collections/347円273円230円345円233円2761円.vsdx" diff --git a/src/resources/io/file/file.vsdx b/src/main/resources/io/file/file.vsdx similarity index 100% rename from src/resources/io/file/file.vsdx rename to src/main/resources/io/file/file.vsdx diff --git a/src/resources/io/file/file01.vsdx b/src/main/resources/io/file/file01.vsdx similarity index 100% rename from src/resources/io/file/file01.vsdx rename to src/main/resources/io/file/file01.vsdx diff --git a/src/resources/io/file/filenameFilter.vsdx b/src/main/resources/io/file/filenameFilter.vsdx similarity index 100% rename from src/resources/io/file/filenameFilter.vsdx rename to src/main/resources/io/file/filenameFilter.vsdx diff --git a/src/resources/io/iostream/iostream.vsdx b/src/main/resources/io/iostream/iostream.vsdx similarity index 100% rename from src/resources/io/iostream/iostream.vsdx rename to src/main/resources/io/iostream/iostream.vsdx diff --git a/test/org/javacore/io/DirectoryTest.java b/src/test/java/org/javacore/io/DirectoryTest.java similarity index 100% rename from test/org/javacore/io/DirectoryTest.java rename to src/test/java/org/javacore/io/DirectoryTest.java diff --git a/src/test/java/org/javacore/param/Param.java b/src/test/java/org/javacore/param/Param.java new file mode 100644 index 0000000..f3ed2a9 --- /dev/null +++ b/src/test/java/org/javacore/param/Param.java @@ -0,0 +1,57 @@ +package org.javacore.param; + +/** + * Created by bysocket on 16/7/18. + */ +public class Param { + Integer id; + + String name; + + Integer age; + + String sex; + + Integer isBeautiful; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + public String getSex() { + return sex; + } + + public void setSex(String sex) { + this.sex = sex; + } + + public Integer getIsBeautiful() { + return isBeautiful; + } + + public void setIsBeautiful(Integer isBeautiful) { + this.isBeautiful = isBeautiful; + } + +} diff --git a/src/test/java/org/javacore/param/ParamService.java b/src/test/java/org/javacore/param/ParamService.java new file mode 100644 index 0000000..cd87d29 --- /dev/null +++ b/src/test/java/org/javacore/param/ParamService.java @@ -0,0 +1,21 @@ +package org.javacore.param; + +/** + * Created by bysocket on 16/7/18. + */ +public class ParamService { + + public void test01(Param param) { + Integer id = param.getId(); + String sex = param.getSex(); + String name = param.getName(); + Integer age = param.getAge(); + Integer isBeautiful = param.getIsBeautiful(); + + + } + + public void test02(Integer id,String sex,String name,Integer age,Integer isBeautiful) { + + } +} diff --git a/src/test/java/org/javacore/param/ParamTest.java b/src/test/java/org/javacore/param/ParamTest.java new file mode 100644 index 0000000..3cd5bfb --- /dev/null +++ b/src/test/java/org/javacore/param/ParamTest.java @@ -0,0 +1,32 @@ +package org.javacore.param; + +import java.util.Date; + +/** + * Created by bysocket on 16/7/18. + */ +public class ParamTest { + + public static void main(String[] args) { + ParamService p = new ParamService(); + + Date start = new Date(); + for (int i = 1 ; i < 1000000; i++) { + p.test02(1,"2","3",4,5); + } + Date end = new Date(); + System.out.println("ParamService.test02() : " + (end.getTime() - start.getTime()) ); + Date start2 = new Date(); + for (int i = 1 ; i < 100000; i++) { + Param param = new Param(); + param.setId(1); + param.setAge(2); + param.setIsBeautiful(1); + param.setName("2"); + param.setSex("2"); + p.test01(param); + } + Date end2 = new Date(); + System.out.println("ParamService.test01() : " + (end2.getTime() - start2.getTime()) ); + } +} diff --git a/test/org/javacore/thread/MyRunnableTest.java b/src/test/java/org/javacore/thread/MyRunnableTest.java similarity index 100% rename from test/org/javacore/thread/MyRunnableTest.java rename to src/test/java/org/javacore/thread/MyRunnableTest.java diff --git a/test/org/javacore/thread/MyThreadTest.java b/src/test/java/org/javacore/thread/MyThreadTest.java similarity index 100% rename from test/org/javacore/thread/MyThreadTest.java rename to src/test/java/org/javacore/thread/MyThreadTest.java diff --git a/src/test/java/org/javacore/time/DurationTest.java b/src/test/java/org/javacore/time/DurationTest.java new file mode 100644 index 0000000..2778646 --- /dev/null +++ b/src/test/java/org/javacore/time/DurationTest.java @@ -0,0 +1,61 @@ +package org.javacore.time; + +import org.junit.Assert; +import org.junit.Test; + +import static org.junit.Assert.fail; + +public class DurationTest { + @Test + public void testCombineTimeUtil() throws Exception { + Assert.assertEquals(Duration.days(1).toMilliseconds(), 24 * 3600 * 1000); + Assert.assertEquals(24 * 3600 * 1000 * 3, Duration.days(3).toMilliseconds()); + Assert.assertEquals(7 * 24 * 3600 * 1000 / 1000, Duration.days(7).toSeconds()); + } + + @Test + public void testValidDurationStrings() throws Exception { + Assert.assertEquals(Duration.of("5ns"), Duration.nanoseconds(5)); + Assert.assertEquals(Duration.of("5microsecond"), Duration.microseconds(5)); + Assert.assertEquals(Duration.of("5milliseconds"), Duration.millis(5)); + Assert.assertEquals(Duration.of("5 seconds"), Duration.seconds(5)); + Assert.assertEquals(Duration.of("5 minutes"), Duration.mins(5)); + Assert.assertEquals(Duration.of("5 hours"), Duration.hours(5)); + Assert.assertEquals(Duration.of("5 days"), Duration.days(5)); + Assert.assertEquals(Duration.of("inf"), Duration.inf()); + Assert.assertEquals(Duration.of("infinite"), Duration.inf()); + Assert.assertEquals(Duration.of("∞"), Duration.infinite()); + + // Interesting value but legal nevertheless + Assert.assertEquals(Duration.of("0s"), Duration.seconds(0)); + } + + private void testInvalidDurationString(String duration) { + try { + Duration.of(duration); + fail("Duration string '" + duration + "' should not parse correctly."); + } catch (IllegalArgumentException iae) { + // Expected + } + } + + @Test + public void testInvalidDurationStrings() { + testInvalidDurationString("foobar"); + testInvalidDurationString("ms3"); + testInvalidDurationString("34 lightyears"); + testInvalidDurationString("34 seconds a day"); + testInvalidDurationString("5 days a week"); + testInvalidDurationString(""); + testInvalidDurationString("2"); + testInvalidDurationString("ns"); + } + + @Test + public void testReplaceOldTimeUtils() { + final int HOUR = 1000 * 60 * 60; + long randomTimestamp = (long) (Math.random() * 400000000L) + 100000; + Assert.assertEquals(randomTimestamp / HOUR, Duration.millis(randomTimestamp).toHours()); + Assert.assertEquals(randomTimestamp / 1000, Duration.millis(randomTimestamp).toSeconds()); + } +} diff --git a/src/test/java/org/javacore/time/InstantTest.java b/src/test/java/org/javacore/time/InstantTest.java new file mode 100644 index 0000000..4df282f --- /dev/null +++ b/src/test/java/org/javacore/time/InstantTest.java @@ -0,0 +1,24 @@ +package org.javacore.time; + +import java.time.Instant; + +/** + * 瞬间类 Instant + * + * Created by bysocket on 16/7/12. + */ +public class InstantTest { + public static void main(String[] args) { + // 获取现在的时间 + Instant now = Instant.now(); + System.out.println(now); + + // 1000000000 年 12月 31日 + Instant max = Instant.MAX; + System.out.println(max); + + // 10亿年前 + Instant min = Instant.MIN; + System.out.println(min); + } +} diff --git a/src/test/java/org/javacore/time/LocalDateTest.java b/src/test/java/org/javacore/time/LocalDateTest.java new file mode 100644 index 0000000..bba3aa8 --- /dev/null +++ b/src/test/java/org/javacore/time/LocalDateTest.java @@ -0,0 +1,29 @@ +package org.javacore.time; + +import java.time.LocalDate; + +/** + * Created by bysocket on 16/8/23. + */ +public class LocalDateTest { + public static void main(String[] args) { + // 今天的日期 + LocalDate localDate = LocalDate.now(); + + System.out.println("今天:" + localDate); + + // 年 + System.out.println("年:" + localDate.getYear()); + // 月 + System.out.println("月:" + localDate.getMonth()); + System.out.println("月:" + localDate.getMonth()); + // 星期 + System.out.println("今天是星期" + localDate.getDayOfWeek()); + + // 距离 + // 年 + System.out.println("今天是今年的第" + localDate.getDayOfYear() + "天"); + // 月 + System.out.println("今天是这个月的第" + localDate.getDayOfMonth() + "天"); + } +} diff --git a/src/test/java/org/javacore/time/LocalDateTest1.java b/src/test/java/org/javacore/time/LocalDateTest1.java new file mode 100644 index 0000000..15467b8 --- /dev/null +++ b/src/test/java/org/javacore/time/LocalDateTest1.java @@ -0,0 +1,18 @@ +package org.javacore.time; + +import java.time.LocalDate; +import java.util.concurrent.TimeUnit; + +/** + * Created by bysocket on 16/8/23. + */ +public class LocalDateTest1 { + public static void main(String[] args) throws InterruptedException { + LocalDate start = LocalDate.now(); + TimeUnit.SECONDS.sleep(3); + LocalDate end = LocalDate.now(); + + System.out.println(start.isAfter(end)); + System.out.println(start.isBefore(end)); + } +} diff --git a/src/test/java/org/javacore/time/LocalDateTest2.java b/src/test/java/org/javacore/time/LocalDateTest2.java new file mode 100644 index 0000000..66bc101 --- /dev/null +++ b/src/test/java/org/javacore/time/LocalDateTest2.java @@ -0,0 +1,17 @@ +package org.javacore.time; + +import java.time.LocalDate; + +/** + * 计算BYSocket的生日是今年的第几天 + * + * Created by bysocket on 16/8/23. + */ +public class LocalDateTest2 { + public static void main(String[] args) { + LocalDate birthdayDate = LocalDate.of(2016,5,2); + System.out.println("BYSocket的生日是今年的第" + birthdayDate.getDayOfYear() + "天"); + // 明年的生日 + System.out.println(birthdayDate.plusYears(1)); + } +} diff --git a/src/test/java/org/javacore/time/PlayDuration.java b/src/test/java/org/javacore/time/PlayDuration.java new file mode 100644 index 0000000..827b56c --- /dev/null +++ b/src/test/java/org/javacore/time/PlayDuration.java @@ -0,0 +1,34 @@ +package org.javacore.time; + +import java.time.Duration; +import java.time.Instant; +import java.util.concurrent.TimeUnit; + +/** + * 持续时间类 Duration + * + * Created by bysocket on 16/8/23. + */ +public class PlayDuration { + public static void main(String[] args) throws InterruptedException { + Instant start = Instant.now(); + TimeUnit.SECONDS.sleep(3); + Instant end = Instant.now(); + + // 获取持续时间 + Duration timeElapsed = Duration.between(start,end); + System.out.println(timeElapsed.toMillis());// 毫秒 + System.out.println(timeElapsed.toNanos());// 纳 + + Instant start1 = Instant.now(); + TimeUnit.SECONDS.sleep(2); + Instant end1 = Instant.now(); + + // 获取持续时间 + Duration timeElapsed1 = Duration.between(start1,end1); + + // 添加操作 + Duration all = timeElapsed.plus(timeElapsed1); + System.out.println(all.toMillis());// 毫秒 + } +} diff --git a/src/test/java/org/javacore/time/TimeUtilTest.java b/src/test/java/org/javacore/time/TimeUtilTest.java new file mode 100644 index 0000000..3716481 --- /dev/null +++ b/src/test/java/org/javacore/time/TimeUtilTest.java @@ -0,0 +1,41 @@ +package org.javacore.time; + +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + +import java.time.LocalDateTime; + +import static org.javacore.time.TimeUtil.TimeFormat.LONG_DATE_PATTERN_DOUBLE_SLASH; +import static org.javacore.time.TimeUtil.TimeFormat.LONG_DATE_PATTERN_SLASH; +import static org.junit.Assert.assertEquals; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class TimeUtilTest { + + @Test + public void testParseSpecificTimeStringByUsingDefaultPattern() throws Exception { + LocalDateTime expectedDateTime = LocalDateTime.of(2014, 11, 11, 10, 11, 11); + LocalDateTime parsedTime = TimeUtil.parseTime("2014-11-11 10:11:11"); + assertEquals(expectedDateTime, parsedTime); + } + + @Test + public void testParseSpecificTimeStringUsingTimeFormat() throws Exception { + LocalDateTime expectedDateTime = LocalDateTime.of(2014, 11, 11, 10, 11, 11); + LocalDateTime parsedTime = TimeUtil.parseTime("2014/11/11 10:11:11", LONG_DATE_PATTERN_SLASH); + assertEquals(expectedDateTime, parsedTime); + } + + @Test + public void testParseLocalDateTimeByUsingDefaultFormatter() throws Exception { + LocalDateTime time = LocalDateTime.of(2014, 11, 11, 10, 11, 11); + assertEquals(TimeUtil.parseTime(time), "2014-11-11 10:11:11"); + } + + @Test + public void testParseLocalDateTimeByUsingTimeFormat() throws Exception { + LocalDateTime time = LocalDateTime.of(2014, 11, 11, 10, 11, 11); + assertEquals(TimeUtil.parseTime(time, LONG_DATE_PATTERN_DOUBLE_SLASH), "2014\11円\11円 10:11:11"); + } +}

AltStyle によって変換されたページ (->オリジナル) /