1.共享变量
将要保存/修改的值set到共享变量中,通过获取共享变量实现值在不同线程中的传递
如下在子线程中循环累加学生年龄,然后在主线程中获取累加后的结果
//共享变量
private static AtomicReference<Student> student = new AtomicReference<>();
private static volatile boolean die = false;
static void updateStudent() {
student.updateAndGet(stu -> {
stu.setAge(stu.getAge() + 1);
return stu;
});
}
public static void main(String[] args) {
Student stu = new Student();
stu.setAge(10);
student.set(stu);
new Thread(() -> {
for (int i = 0; i < 90; i++) {
updateStudent();
}
die = true;
}).start();
while (true) {
if (die) {
System.out.println("年龄:" + student.get().getAge());
break;
}
}
}
2.FutureTask
先看代码
FutureTask<Student> futureTask = new FutureTask<>(new Callable<Student>() {
@Override
public Student call() throws Exception {
Student student = new Student();
student.setName("zhangSan");
student.setAge(10);
student.setSex("man");
Thread.sleep(1000);
return student;
}
});
new Thread(futureTask).start();
while (true) {
if (futureTask.isDone()) {
Student student = futureTask.get();
System.out.println(student);
break;
}
}
new Thread(futureTask).start()
可以看出FutureTask 一定实现了Runnable接口, 创建FutureTask 需要一个Callable 参数,Callable 是一个Function接口只有一个call方法,我们的业务代码写在call 方法里,所以调用逻辑应该是
thread.start() -> futureTask.run() -> callable.call()
线程启动,调用run方法,run方法内部调用call 方法
Futuretask的run方法部分代码
......
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
//调用callable.call()
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
//设置异常信息,状态等
setException(ex);
}
if (ran)
//设置返回值,状态等
set(result);
}
}
......
Future
Futuretask 除了实现Runable还实现了Future接口,future有如下接口
boolean cancel(boolean mayInterruptIfRunning); 尝试取消执行这个任务,如果线程已经执行完毕或者已经取消会取消失败,如果任务已经开始,则根据mayInterruptIfRunning执行是否取消,需要注意的是这里的取消相当于thread.interrupt(),并不能停止任务,当然如果任务还没有开始执行那么取消是成功的.
boolean isCancelled(); 任务是否被取消
boolean isDone(); 任务是否执行完成,任务正常执行完,被取消或抛出异常都会返回true
V get() ; 获取返回值,需要注意的是这是一个阻塞的方法,会抛InterruptedException
V get(long timeout, TimeUnit unit) 与get方法一样,可以设置等待时间,超时会抛TimeoutException
3.线程池-ThreadPool
向线程池提交线程会返回一个上面说的Future对象,通过Future获取返回值
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 5, 5L, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(5),
new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
return thread;
}
});
//提交任务,获得Future
Future<Integer> submit = threadPoolExecutor.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return 100;
}
});
while (true) {
if (submit.isDone()) {
System.out.println(submit.get());
break;
}
}
转载请注明出处