码迷,mamicode.com
首页 > 编程语言 > 详细

java线程实现的四种方式

时间:2018-05-22 12:39:15      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:ring   四种   read   res   adp   over   执行   print   获取   

  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");
    }
}

 

java线程实现的四种方式

标签:ring   四种   read   res   adp   over   执行   print   获取   

原文地址:https://www.cnblogs.com/codeLei/p/9070634.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!