CodeZLei

  博客园 :: 首页 :: 博问 :: 闪存 :: :: 联系 :: 订阅 订阅 :: 管理 ::

  java多线程的实现可以通过以下四种方式

    1.继承Thread类,重写run方法

    2.实现Runnable接口,重写run方法

    3.通过Callable和FutureTask创建线程

    4.通过线程池创建线程

  方式1,2不再赘述.

  方式3,通过Callable和FutureTask创建线程实现多线程

    @Test
    public void MyCallableTest() throws Exception {
        //创建线程执行对象
        MyCallable myCallable = new MyCallable();
        FutureTask<String> futureTask = new FutureTask<>(myCallable);
        //执行线程
        Thread thread = new Thread(futureTask);
        thread.start();
        //获取线程方法返回数据
        System.out.println(futureTask.get());
    }
    /**
     * 创建实现类
     */
    class MyCallable implements Callable<String>{
        @Override
        public String call() throws Exception {
            System.out.println("test thread by callable");
            return "result";
        }
    }

  方式4,通过线程池创建线程

public class ThreadPoolStu {

    @Test
    public void TestThreadPool1() throws InterruptedException, ExecutionException {
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        
        //执行Runnable接口实现类 方式1
        MyRunnable runnable1 = new MyRunnable();
        executorService.execute(runnable1);
        
        //执行Runnable接口实现类 方式2
        MyRunnable runnable2 = new MyRunnable();
        Future<?> future2 = executorService.submit(runnable2);
        System.out.println(future2.get());//若未执行完会阻塞该线程
        
        //执行Callable接口实现类
        MyCallable callable3 = new MyCallable();
        Future<String> future3 = executorService.submit(callable3);
        System.out.println(future3.get());//若未执行完会阻塞该线程
        
        // 关闭线程池
        executorService.shutdown();
    }

}
class MyCallable implements Callable<String>{
    @Override
    public String call() throws Exception {
        System.out.println("test thread by callable");
        return "result";
    }
}
class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("thread execute");
    }
}

 

posted on 2018-05-22 10:09  CodeZLei  阅读(335)  评论(0编辑  收藏  举报