线程目前是我的薄弱点吧,前天看了视频,昨天忙着没跟着再重写,今天有空就写了个。
难倒是不难,大部分能推理出来,不过一些点上能感觉出自己对这一块的确是很薄弱,需要加强。
FutureTask 和 Callable 原始版本
public static void main(String[] args) throws Exception{
FutureTask task1 = new FutureTask(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Integer num = 0;
Thread.sleep(5000);
num++;
System.out.println("num = "+num+" 已跑完");
return num;
}
});
new Thread(task1).start();
System.out.println(Thread.currentThread() + " 已完成,task结果: "+task1.get());
}
自写版本
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.LockSupport;
public class MyFutureTask<T> implements Runnable {
private MyCallable<T> myCallable;
private T result;
private volatile LinkedBlockingQueue<Thread> threads = new LinkedBlockingQueue<>();
private String state;
public MyFutureTask(MyCallable<T> myCallable){
this.myCallable = myCallable;
}
@Override
public void run() {
try {
state = "RUN";
result = myCallable.call();
threads.add(Thread.currentThread());
} catch (Exception e) {
e.printStackTrace();
}finally {
state = "END";
//任务结束,通知不要等待
Thread waiter = threads.poll(); //取数据
while (waiter != null){
LockSupport.unpark(waiter);
waiter = threads.poll();
}
}
}
public T get()throws Exception{
//获取结果之前需要确保线程已经跑完
threads.add(Thread.currentThread());
while (!"END".equals(state)){
LockSupport.park();
}
return result;
}
}
public class MyFutureTask<T> implements Runnable {
private MyCallable<T> myCallable;
private T result;
private LinkedBlockingQueue<Thread> threads = new LinkedBlockingQueue<>();
private String state;
public MyFutureTask(MyCallable<T> myCallable){
this.myCallable = myCallable;
}
@Override
public void run() {
try {
state = "RUN";
result = myCallable.call();
threads.add(Thread.currentThread());
} catch (Exception e) {
e.printStackTrace();
}finally {
state = "END";
//任务结束,通知不要等待
Thread waiter = threads.poll(); //取数据
while (waiter != null){
LockSupport.unpark(waiter);
waiter = threads.poll();
}
}
}
public T get()throws Exception{
//获取结果之前需要确保线程已经跑完
threads.add(Thread.currentThread());
while (!"END".equals(state)){
LockSupport.park();
}
return result;
}
}
测试
public static void main(String[] args) throws Exception{
MyFutureTask task = new MyFutureTask(new MyCallable<Integer>(){
@Override
public Integer call() throws Exception{
Integer num = 0;
Thread.sleep(5000);
num++;
System.out.println("num = "+num+" 已跑完");
return num;
}
});
new Thread(task).start();
System.out.println(Thread.currentThread() + " 已完成,task结果: "+task.get());
}