带你快速搞定java多线程(2)

时间:2022-09-23 14:58:42

1、Future的类图结构,从整体上看下Future的结构

带你快速搞定java多线程(2)

带你快速搞定java多线程(2)

首先看下future接口的函数,共有5个方法。

get() 获取执行的结果,另外一个重载是有时间限制的get ,如果超时会有异常

isDone() 判断future 结果是否处理完成

cancel 取消任务

2、future的使用,说的再多都么什么用,来个例子悄悄怎么用的。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package thread;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* @author 香菜
*/
public class FutureTest {
private ExecutorService bossExecutor = Executors.newSingleThreadExecutor();
public Future<Integer> getHpTask(Integer input) {
return bossExecutor.submit(() -> {
System.out.println("Calculating..." + input);
Thread.sleep(1000);
return input * input;
});
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
Future<Integer> calculate = new FutureTest().getHpTask(100);
System.out.println(calculate.get());
System.out.println("Done");
}
}

3、通俗理解

future 就像是去买手抓饼,你把钱给老板之后,老板对你说我做好了之后会放在旁边的盘子里,而这个盘子就是future,你用isDone 判断盘子里是不是有你要的手抓饼,有的话你就拿走。当然你可以一直在那等着 get(),或者去做其他的事情,等会再来拿。

4、原理

看下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public V get() throws InterruptedException, ExecutionException {
      int s = state;
      if (s <= COMPLETING)
          s = awaitDone(false, 0L);
      return report(s);
  }
  private int awaitDone(boolean timed, long nanos)
      throws InterruptedException {
      final long deadline = timed ? System.nanoTime() + nanos : 0L;
      WaitNode q = null;
      boolean queued = false;
      for (;;) {
          if (Thread.interrupted()) {
              removeWaiter(q);
              throw new InterruptedException();
          }
          int s = state;
          if (s > COMPLETING) {
              if (q != null)
                  q.thread = null;
              return s;
          }
          else if (s == COMPLETING) // cannot time out yet
              Thread.yield();
          else if (q == null)
              q = new WaitNode();
          else if (!queued)
              queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                    q.next = waiters, q);
          else if (timed) {
              nanos = deadline - System.nanoTime();
              if (nanos <= 0L) {
                  removeWaiter(q);
                  return state;
              }
              LockSupport.parkNanos(this, nanos);
          }
          else
              LockSupport.park(this);
      }
  }

看下上面的代码就是在获取结果的时候,会先判断状态是否完成,如果完成了就正常返回结果,如果没完成就会调用awaitDone,看名字也能看出来就是等待直到完成,进入代码可以看到就是将进入死循环检查状态,线程阻塞等待,直到完成。要你写你是不是也会这样写?

5、总结

本篇文章就到这里了,希望能给你带来帮助,也希望您能够多多关注服务器之家的更多内容!

原文链接:https://gamwatcher.blog.csdn.net/article/details/114682253