Java内容重新整理删除过期的东西

This commit is contained in:
estom
2025-09-14 03:49:42 -04:00
parent 9b8524ff80
commit 885b795e45
413 changed files with 643 additions and 1340 deletions

View File

@@ -0,0 +1,78 @@
package cn.aofeng.demo.java.util.concurret;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import cn.aofeng.demo.util.DateUtil;
/**
* {@link ScheduledExecutorService}的使用示例:<br>
* 定时任务1执行过程中会抛出异常。<br>
* 定时任务2执行过程中不会抛出异常。<br>
* <br>
* 目的检测java.util.concurrent.ScheduledExecutorService在执行定时任务的过程中任务内抛出异常没有捕捉时在下一次执行时间到来时是否可以正常执行。<br>
* 测试的JDK版本1.6.xx。<br>
* 结果通过相比java.util.Timer完善地解决了定时任务抛异常的问题。
*
* @author <a href="mailto:aofengblog@163.com">聂勇</a>
*/
public class ScheduledExecutorServiceDemo {
public static void main(String[] args) {
ScheduledExecutorService timer = Executors.newScheduledThreadPool(2);
long delay = computeDelay();
timer.schedule(new ThrowExceptionTask(timer), delay, TimeUnit.MILLISECONDS);
timer.schedule(new NotThrowExceptionTask(timer), delay, TimeUnit.MILLISECONDS);
System.out.println("主线程的功能执行完毕");
}
private static long computeDelay() {
Date now = new Date();
Date nextMinute = DateUtil.getNextMinute();
long delay = nextMinute.getTime() - now.getTime();
return delay;
}
static class ThrowExceptionTask implements Runnable {
private ScheduledExecutorService _timer;
public ThrowExceptionTask(ScheduledExecutorService timer) {
this._timer = timer;
}
@Override
public void run() {
try {
System.out.println("任务名:ThrowExceptionTask, 当前时间:"+DateUtil.getCurrentTime());
throw new IllegalArgumentException();
} finally {
_timer.schedule(new ThrowExceptionTask(_timer), computeDelay(), TimeUnit.MILLISECONDS);
}
}
} // end of ThrowExceptionTask
static class NotThrowExceptionTask implements Runnable {
private ScheduledExecutorService _timer;
public NotThrowExceptionTask(ScheduledExecutorService timer) {
this._timer = timer;
}
@Override
public void run() {
try {
System.out.println("任务名:NotThrowExceptionTask, 当前时间:"+DateUtil.getCurrentTime());
} finally {
_timer.schedule(new NotThrowExceptionTask(_timer), computeDelay(), TimeUnit.MILLISECONDS);
}
}
} // end of NotThrowExceptionTask
}

View File

@@ -0,0 +1,103 @@
package cn.aofeng.demo.java.util.forkjoin;
import java.util.Arrays;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.TimeUnit;
/**
* Fork/Join练习。
*
* @author <a href="mailto:aofengblog@163.com">聂勇</a>
*/
public class HelloForkJoin extends RecursiveTask<Long> {
private static final long serialVersionUID = -2386438994963147457L;
private int[] _intArray;
private int _threshold = 10;
private long _result = 0;
public HelloForkJoin(int[] intArray) {
this._intArray = intArray;
}
@Override
protected Long compute() {
if (null == _intArray || _intArray.length <= 0) {
return 0L;
}
if (_intArray.length <= _threshold) { // 如果数组长度小于等于指定的值,执行累加操作
for (int item : _intArray) {
_result += item;
}
System.out.println( String.format("线程:%s累加数组%s中的值结果%d", Thread.currentThread(), Arrays.toString(_intArray), _result) );
} else { // 如果数组长度大于指定的值,做任务分解
int[] temp = new int[_threshold];
System.arraycopy(_intArray, 0, temp, 0, _threshold);
HelloForkJoin subTask1 = new HelloForkJoin(temp);
subTask1.fork();
if (_intArray.length - _threshold > 0) {
int remain[] = new int[_intArray.length - _threshold];
System.arraycopy(_intArray, _threshold, remain, 0, remain.length);
HelloForkJoin task = new HelloForkJoin(remain);
task.fork();
_result += task.join();
}
_result += subTask1.join();
return _result;
}
return _result;
}
public static void main(String[] args) throws InterruptedException {
int count = 10000;
serialCompute(count);
parallelCompute(count);
}
/**
* 使用fork/join并行计算数字累加。
*
* @param count 数字个数从1开始
* @throws InterruptedException
*/
private static void parallelCompute(int count)
throws InterruptedException {
int[] numbers = new int[count];
for (int i = 0; i < count; i++) {
numbers[i] = i+1;
}
ForkJoinPool pool = new ForkJoinPool(4);
HelloForkJoin task = new HelloForkJoin(numbers);
long startTime = System.currentTimeMillis();
pool.submit(task);
pool.shutdown();
pool.awaitTermination(10, TimeUnit.SECONDS);
System.out.println( String.format("并行计算结果:%d耗时%d毫秒", task._result, System.currentTimeMillis()-startTime) );
}
/**
* 使用for循环串行计算数字累加。
*
* @param count 数字个数从1开始
*/
private static void serialCompute(int count) {
long startTime = System.currentTimeMillis();
int sum = 0;
for (int i = 0; i < count; i++) {
sum += (i+1);
}
System.out.println( String.format("串行计算结果:%d耗时%d毫秒", sum, System.currentTimeMillis()-startTime) );
}
}

View File

@@ -0,0 +1,101 @@
<?xml version="1.0" encoding="UTF-8"?>
<class-diagram version="1.1.6" icons="true" always-add-relationships="false" generalizations="true" realizations="true"
associations="true" dependencies="false" nesting-relationships="true">
<interface id="1" language="java" name="java.util.concurrent.Future" project="JavaDemo"
file="/devdata/java/jdk/jdk1.7.0_60/jre/lib/rt.jar" binary="true" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="334" y="85"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" accessors="true"
visibility="true">
<attributes public="false" package="true" protected="false" private="false" static="false"/>
<operations public="true" package="true" protected="false" private="false" static="false"/>
</display>
</interface>
<class id="2" language="java" name="java.util.concurrent.FutureTask" project="JavaDemo"
file="/devdata/java/jdk/jdk1.7.0_60/jre/lib/rt.jar" binary="true" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="521" y="477"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" accessors="true"
visibility="true">
<attributes public="false" package="true" protected="false" private="false" static="false"/>
<operations public="true" package="true" protected="false" private="false" static="false"/>
</display>
</class>
<interface id="3" language="java" name="java.util.concurrent.RunnableFuture" project="JavaDemo"
file="/devdata/java/jdk/jdk1.7.0_60/jre/lib/rt.jar" binary="true" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="521" y="280"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" accessors="true"
visibility="true">
<attributes public="false" package="true" protected="false" private="false" static="false"/>
<operations public="true" package="true" protected="false" private="false" static="false"/>
</display>
</interface>
<interface id="4" language="java" name="java.util.concurrent.RunnableScheduledFuture" project="JavaDemo"
file="/devdata/java/jdk/jdk1.7.0_60/jre/lib/rt.jar" binary="true" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="130" y="410"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" accessors="true"
visibility="true">
<attributes public="false" package="true" protected="false" private="false" static="false"/>
<operations public="true" package="true" protected="false" private="false" static="false"/>
</display>
</interface>
<interface id="5" language="java" name="java.util.concurrent.ScheduledFuture" project="JavaDemo"
file="/devdata/java/jdk/jdk1.7.0_60/jre/lib/rt.jar" binary="true" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="131" y="272"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" accessors="true"
visibility="true">
<attributes public="false" package="true" protected="false" private="false" static="false"/>
<operations public="true" package="true" protected="false" private="false" static="false"/>
</display>
</interface>
<interface id="6" language="java" name="java.util.concurrent.Delayed" project="JavaDemo"
file="/devdata/java/jdk/jdk1.7.0_60/jre/lib/rt.jar" binary="true" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="131" y="119"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" accessors="true"
visibility="true">
<attributes public="false" package="true" protected="false" private="false" static="false"/>
<operations public="true" package="true" protected="false" private="false" static="false"/>
</display>
</interface>
<interface id="7" language="java" name="java.lang.Runnable" project="JavaDemo"
file="/devdata/java/jdk/jdk1.7.0_60/jre/lib/rt.jar" binary="true" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="521" y="119"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" accessors="true"
visibility="true">
<attributes public="false" package="true" protected="false" private="false" static="false"/>
<operations public="true" package="true" protected="false" private="false" static="false"/>
</display>
</interface>
<generalization id="8">
<end type="SOURCE" refId="4"/>
<end type="TARGET" refId="5"/>
</generalization>
<generalization id="9">
<end type="SOURCE" refId="3"/>
<end type="TARGET" refId="7"/>
</generalization>
<generalization id="10">
<end type="SOURCE" refId="4"/>
<end type="TARGET" refId="3"/>
</generalization>
<generalization id="11">
<end type="SOURCE" refId="5"/>
<end type="TARGET" refId="6"/>
</generalization>
<generalization id="12">
<end type="SOURCE" refId="5"/>
<end type="TARGET" refId="1"/>
</generalization>
<generalization id="13">
<end type="SOURCE" refId="3"/>
<end type="TARGET" refId="1"/>
</generalization>
<realization id="14">
<end type="SOURCE" refId="2"/>
<end type="TARGET" refId="3"/>
</realization>
<classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
accessors="true" visibility="true">
<attributes public="false" package="true" protected="false" private="false" static="false"/>
<operations public="true" package="true" protected="false" private="false" static="false"/>
</classifier-display>
<association-display labels="true" multiplicity="true"/>
</class-diagram>

View File

@@ -0,0 +1,106 @@
package cn.aofeng.demo.java.util.future;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
/**
* Future、Callable练习。
*
* @author <a href="mailto:aofengblog@163.com">聂勇</a>
*/
public class HelloFuture {
private static Logger _logger = Logger.getLogger(HelloFuture.class);
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
executeSingleTask();
executeBatchTask();
}
/**
* 执行单个异步任务:<br>
* 1、用submit方法向线程池提交一个任务。<br>
* 2、获取结果时指定了超时时间。<br><br>
* 结果超时后调用者收到TimeoutException但实际上任务还在继续执行。
* @throws InterruptedException
*/
private static void executeSingleTask() throws InterruptedException {
ExecutorService threadpool = Executors.newFixedThreadPool(6);
try {
Future<Integer> f = threadpool.submit(createCallable(5 * 1000));
Object result = f.get(3, TimeUnit.SECONDS);
System.out.println("单个任务的执行结果:"+result);
} catch (Exception e) {
_logger.error("线程执行任务时出错", e);
} finally {
threadpool.shutdown();
threadpool.awaitTermination(10, TimeUnit.SECONDS);
}
}
/**
* 执行多个异步任务:<br>
* 1、用invokeAll方法向线程池提交多个任务并指定了执行的超时时间。<br><br>
* 结果超时后未执行完成的任务被取消在调用Future的get方法时取消的任务会抛出CancellationException执行完成的任务可获得结果。
* @throws InterruptedException
*/
private static void executeBatchTask() throws InterruptedException {
ExecutorService threadpool = Executors.newFixedThreadPool(6);
List<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>();
tasks.add(createCallable(2000));
tasks.add(createCallable(5000));
tasks.add(createCallable(2500));
long startTime = System.currentTimeMillis();
try {
List<Future<Integer>> fs = threadpool.invokeAll(tasks, 3, TimeUnit.SECONDS);
int result = 0;
for (Future<Integer> f : fs) {
try{
result += f.get();
} catch(CancellationException ce) {
// nothing
}
}
System.out.println("执行三个任务共耗时:" + (System.currentTimeMillis() - startTime) + "毫秒");
System.out.println("三个任务的执行结果汇总:"+result);
} catch (Exception e) {
_logger.error("线程执行任务时出错", e);
} finally {
threadpool.shutdown();
threadpool.awaitTermination(10, TimeUnit.SECONDS);
}
}
/**
* 创建需要长时间执行的任务模拟对象。
* @param sleepTimes 线程休眠时间(单位:毫秒)
* @return {@link Callable}对象
*/
private static Callable<Integer> createCallable(final int sleepTimes) {
Callable<Integer> c = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Thread.sleep(sleepTimes);
System.out.println(Thread.currentThread().getName() + ": I'm working");
return 9;
}
};
return c;
}
}

View File

@@ -0,0 +1,139 @@
<?xml version="1.0" encoding="UTF-8"?>
<class-diagram version="1.1.6" icons="true" always-add-relationships="false" generalizations="true" realizations="true"
associations="true" dependencies="false" nesting-relationships="true">
<interface id="1" language="java" name="java.util.Map" project="JavaDemo"
file="/devdata/java/jdk/jdk1.6.0_45/jre/lib/rt.jar" binary="true" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="417" y="179"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" accessors="true"
visibility="true">
<attributes public="false" package="false" protected="false" private="false" static="true"/>
<operations public="true" package="true" protected="false" private="false" static="true"/>
</display>
</interface>
<class id="2" language="java" name="java.util.AbstractMap" project="JavaDemo"
file="/devdata/java/jdk/jdk1.6.0_45/jre/lib/rt.jar" binary="true" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="417" y="423"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" accessors="true"
visibility="true">
<attributes public="false" package="false" protected="false" private="false" static="true"/>
<operations public="false" package="false" protected="false" private="false" static="true"/>
</display>
</class>
<class id="3" language="java" name="java.util.HashMap" project="JavaDemo"
file="/devdata/java/jdk/jdk1.6.0_45/jre/lib/rt.jar" binary="true" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="824" y="422"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" accessors="true"
visibility="true">
<attributes public="false" package="false" protected="false" private="false" static="false"/>
<operations public="false" package="false" protected="false" private="false" static="true"/>
</display>
</class>
<class id="4" language="java" name="java.util.Hashtable" project="JavaDemo"
file="/devdata/java/jdk/jdk1.6.0_45/jre/lib/rt.jar" binary="true" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="152" y="312"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" accessors="true"
visibility="true">
<attributes public="false" package="false" protected="false" private="false" static="true"/>
<operations public="false" package="false" protected="false" private="false" static="true"/>
</display>
</class>
<class id="5" language="java" name="java.util.IdentityHashMap" project="JavaDemo"
file="/devdata/java/jdk/jdk1.6.0_45/jre/lib/rt.jar" binary="true" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="206" y="423"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" accessors="true"
visibility="true">
<attributes public="false" package="false" protected="false" private="false" static="true"/>
<operations public="false" package="false" protected="false" private="false" static="true"/>
</display>
</class>
<class id="6" language="java" name="java.util.LinkedHashMap" project="JavaDemo"
file="/devdata/java/jdk/jdk1.6.0_45/jre/lib/rt.jar" binary="true" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="824" y="283"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" accessors="true"
visibility="true">
<attributes public="false" package="false" protected="false" private="false" static="true"/>
<operations public="false" package="false" protected="false" private="false" static="true"/>
</display>
</class>
<class id="7" language="java" name="java.util.EnumMap" project="JavaDemo"
file="/devdata/java/jdk/jdk1.6.0_45/jre/lib/rt.jar" binary="true" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="329" y="528"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" accessors="true"
visibility="true">
<attributes public="false" package="false" protected="false" private="false" static="true"/>
<operations public="false" package="false" protected="false" private="false" static="true"/>
</display>
</class>
<class id="8" language="java" name="java.util.TreeMap" project="JavaDemo"
file="/devdata/java/jdk/jdk1.6.0_45/jre/lib/rt.jar" binary="true" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="499" y="526"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" accessors="true"
visibility="true">
<attributes public="false" package="false" protected="false" private="false" static="true"/>
<operations public="false" package="false" protected="false" private="false" static="true"/>
</display>
</class>
<class id="9" language="java" name="java.util.WeakHashMap" project="JavaDemo"
file="/devdata/java/jdk/jdk1.6.0_45/jre/lib/rt.jar" binary="true" corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="609" y="374"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true" accessors="true"
visibility="true">
<attributes public="false" package="false" protected="false" private="false" static="true"/>
<operations public="false" package="false" protected="false" private="false" static="true"/>
</display>
</class>
<generalization id="10">
<end type="SOURCE" refId="9"/>
<end type="TARGET" refId="2"/>
</generalization>
<generalization id="11">
<end type="SOURCE" refId="8"/>
<end type="TARGET" refId="2"/>
</generalization>
<realization id="12">
<end type="SOURCE" refId="5"/>
<end type="TARGET" refId="1"/>
</realization>
<generalization id="13">
<end type="SOURCE" refId="3"/>
<end type="TARGET" refId="2"/>
</generalization>
<realization id="14">
<end type="SOURCE" refId="4"/>
<end type="TARGET" refId="1"/>
</realization>
<realization id="15">
<end type="SOURCE" refId="2"/>
<end type="TARGET" refId="1"/>
</realization>
<realization id="16">
<end type="SOURCE" refId="3"/>
<end type="TARGET" refId="1"/>
</realization>
<generalization id="17">
<end type="SOURCE" refId="7"/>
<end type="TARGET" refId="2"/>
</generalization>
<realization id="18">
<end type="SOURCE" refId="9"/>
<end type="TARGET" refId="1"/>
</realization>
<generalization id="19">
<end type="SOURCE" refId="6"/>
<end type="TARGET" refId="3"/>
</generalization>
<generalization id="20">
<end type="SOURCE" refId="5"/>
<end type="TARGET" refId="2"/>
</generalization>
<realization id="21">
<end type="SOURCE" refId="6"/>
<end type="TARGET" refId="1"/>
</realization>
<classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
accessors="true" visibility="true">
<attributes public="true" package="true" protected="false" private="false" static="true"/>
<operations public="true" package="true" protected="false" private="false" static="true"/>
</classifier-display>
<association-display labels="true" multiplicity="true"/>
</class-diagram>

View File

@@ -0,0 +1,47 @@
package cn.aofeng.demo.java.util.timer;
import java.util.Timer;
import java.util.TimerTask;
import cn.aofeng.demo.util.DateUtil;
/**
* {@link Timer}的使用示例:<br>
* 定时任务1执行过程中会抛出异常。<br>
* 定时任务2执行过程中不会抛出异常。<br>
* <br>
* 目的检测java.util.Timer在执行定时任务的过程中任务内抛出异常没有捕捉时在下一次执行时间到来时是否可以正常执行。<br>
* 测试的JDK版本1.6.xx。<br>
* 结果不通过定时任务抛出异常时整个Timer中止其他定时任务也中止。
*
* @author <a href="mailto:aofengblog@163.com">聂勇</a>
*/
public class TimerDemo {
public static void main(String[] args) {
Timer timer = new Timer("aofeng-timer-demo");
timer.schedule(new ThrowExceptionTask(), DateUtil.getNextMinute(), 60*1000);
timer.schedule(new NotThrowExceptionTask(), DateUtil.getNextMinute(), 60*1000);
}
static class ThrowExceptionTask extends TimerTask {
@Override
public void run() {
System.out.println("任务名:ThrowExceptionTask, 当前时间:"+DateUtil.getCurrentTime());
throw new IllegalArgumentException();
}
} // end of ThrowExceptionTask
static class NotThrowExceptionTask extends TimerTask {
@Override
public void run() {
System.out.println("任务名:NotThrowExceptionTask, 当前时间:"+DateUtil.getCurrentTime());
}
} // end of NotThrowExceptionTask
}