本文主要根据《Java程序员修炼之道》整理的代码笔记片段
工作单元
public class WorkUnit<T> {
private final T workUnit;
public T getWork() {
return workUnit;
}
public WorkUnit(T _workUnit) {
workUnit = _workUnit;
}
}
计划线程池(启动、关闭、执行队列中工作单元)
public class ScheduledThreadPoolExecutorClass {
private ScheduledExecutorService stpe;
private ScheduledFuture<?> hndl;
BlockingQueue<WorkUnit<String>> lbq =
new LinkedBlockingQueue<>();
private void run(){
stpe = Executors.newScheduledThreadPool(2);
final Runnable msgReader = new Runnable() {
@Override
public void run() {
String nextMsg = lbq.poll().getWork();
if(nextMsg != null){
System.out.println("Msg recvd: "+ nextMsg);
}
}
};
hndl =stpe.scheduleAtFixedRate(msgReader, 10, 10, TimeUnit.MILLISECONDS);
}
private void cancel(){
final ScheduledFuture<?> myHndl = hndl;
stpe.schedule(new Runnable() {
@Override
public void run() {
myHndl.cancel(true);
}
}, 10, TimeUnit.MILLISECONDS);
}
public static void main(String[] args) {
ScheduledThreadPoolExecutorClass s = new ScheduledThreadPoolExecutorClass();
for (int i = 0; i < 10; i++) {
s.lbq.add(new WorkUnit<String>(i+""));
}
s.run();
for (int i = 10; i < 20; i++) {
s.lbq.add(new WorkUnit<String>(i+""));
}
}
}
think in java 实例 Callable
/*
The submit( ) method produces a Future object,
parameterized for the particular type of result
returned by the Callable. You can query the
Future with isDone( ) to see if it has completed.
When the task is completed and has a result,
you can call get( ) to fetch the result.
You can simply call get( ) without checking isDone( ),
in which case get( ) will block until the result is ready.
You can also call get( ) with a timeout,
or isDone( ) to see if the task has completed,
before trying to call get( ) to fetch the result.
The overloaded Executors.callable( ) method
takes a Runnable and produces a Callable.
ExecutorService has some "invoke" methods
that run collections of Callable objects.
*/
public class CallableDemo {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
ArrayList<Future<String>> results = new ArrayList<Future<String>>();
for (int i = 0; i < 10; i++)
results.add(exec.submit(new TaskWithResult(i)));
for (Future<String> fs : results)
try {
// get() blocks until completion:
System.out.println(fs.get());
} catch (InterruptedException e) {
System.out.println(e);
return;
} catch (ExecutionException e) {
System.out.println(e);
} finally {
exec.shutdown();
}
}
}
class TaskWithResult implements Callable<String> {
private int id;
public TaskWithResult(int id) {
this.id = id;
}
public String call() {
return "result of TaskWithResult " + id;
}
}