多线程(一) 创建多线程

1.继承Thread,重新run方法

2.实现Runnable方法

3.FutureTask实现Future

 public void testCallBack() {
        final FutureTask<String> futureTask = new FutureTask<>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                int i = 0;
                while (i < 100) {
                    i++;
                }
                return i+"";
            }
        });

        new Thread(futureTask).start();
 
        //FutureTask实现了Callbale和Runnable接口
     
        boolean done = futureTask.isDone();//如果Task完成,返回true
        boolean cancelled = futureTask.isCancelled();//正常完成前被取消,返回true
        futureTask.cancel(true); //试图取消Future关联的Callable任务
         try {
            futureTask.get(2000, TimeUnit.SECONDS);//阻塞方法,超过该时间没有返回值则报错
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }

    }
  Task task = new Task();
        ExecutorService executorService = Executors.newCachedThreadPool();
 
        Future<String> future = executorService.submit(task);
        try {
            //阻塞方法
            String result = future.get();
            Log.d(TAG, "future result = " + result);
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

 

上一篇:AES-加密解密工具类


下一篇:java反射初探