###线程共享数据
Java中共享数据,可以使用一个共享对象,或者使用一个阻塞队列。接下来看一个日志的例子。其中主线程可以记录日志,而另外开启了一个线程进行日志输出
public class LogService {
private final BlockingQueue<String> queue;
private final LoggerThread logger;
//关闭标记
private volatile boolean isShutDown;
public void start() {
logger.start();
}
public void stop() {
isShutDown = true;
logger.interrupt();
}
public void log(String msg) throws InterruptedException {
queue.put(msg);
}
public LogService() {
queue = new LinkedBlockingQueue<String>();
logger = new LoggerThread();
}
private class LoggerThread extends Thread {
@Override
public void run() {
try {
while (true) {
if (isShutDown)
break;
System.out.println(queue.take());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
###延迟处理
有时一个任务开启一个线程执行,需要等待数据返回再进行处理,但又希望主线程可以继续跑下去。这时可以使用Future进行处理。代码
public class GetData {
private final ExecutorService executor = Executors.newSingleThreadExecutor();
public Future<String> getData() {
return executor.submit(new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println("my data!");
return "hello world!";
}
});
}
}
测试
public static void main(String[] args) throws InterruptedException, ExecutionException {
GetData data = new GetData();
Future<String> future = data.getData();
//做其他事情
System.out.println("do something!");
String str = future.get();
System.out.println(str);
}
###其他参考
《Java并发编程实战》