大家好,我是小黑,一个在互联网苟且偷生的农民工。
Runnable
在创建线程时,可以通过new Thread(Runnable)
方式,将任务代码封装在Runnable
的run()
方法中,将Runnable
作为任务提交给Thread
,或者使用线程池的execute(Runnable)
方法处理。
public class RunnableDemo {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.submit(new MyRunnable());
}
}
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("runnable正在执行");
}
}
Runnable的问题
如果你之前有看过或者写过Runnable相关的代码,肯定会看到有说Runnable不能获取任务执行结果的说法,这就是Runnable存在的问题,那么可不可以改造一下来满足使用Runnable并获取到任务的执行结果呢?答案是可以的,但是会比较麻烦。
首先我们不能修改run()
方法让它有返回值,这违背了接口实现的原则;我们可以通过如下三步完成:
- 我们可以在自定义的
Runnable
中定义变量,存储计算结果; - 对外提供方法,让外部可以通过方法获取到结果;
- 在任务执行结束之前如果外部要获取结果,则进行阻塞;
如果你有看过我之前的文章,相信要做到功能并不复杂,具体实现可以看我下面的代码。
public class RunnableDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyRunnable<String> myRunnable = new MyRunnable<>();
new Thread(myRunnable).start();
System.out.println(LocalDateTime.now() + " myRunnable启动~");
MyRunnable.Result<String> result = myRunnable.getResult();
System.out.println(LocalDateTime.now() + " " + result.getValue());
}
}
class MyRunnable<T> implements Runnable {
// 使用result作为返回值的存储变量,使用volatile修饰防止指令重排
private volatile Result<T> result;
@Override
public void run() {
// 因为在这个过程中会对result进行赋值,保证在赋值时外部线程不能获取,所以加锁
synchronized (this) {
try {
TimeUnit.SECONDS.sleep(2);
System.out.println(LocalDateTime.now() + " run方法正在执行");
result = new Result("这是返回结果");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 赋值结束后唤醒等待线程
this.notifyAll();
}
}
}
// 方法加锁,只能有一个线程获取
public synchronized Result<T> getResult() throws InterruptedException {
// 循环校验是否已经给结果赋值
while (result == null) {
// 如果没有赋值则等待
this.wait();
}
return result;
}
// 使用内部类