实现多线程的三种方式

自己玩的阿里云到期了,疫情原因,降薪,租不起了,总结到上面的一些技术没同步下来,以后回归最开始的博客园,转战这里总结,下面看看多线程相关的东西。

实现多线程可采取以下方式

a.继承Thread [θred]

b.实现Runnable ['rʌnəbl] 

c.实现Callable ['kɔːləb(ə)l]

a方式线程执行完后没有返回结果,c有线程执行后的返回结果。

========================================================================

a:

 1     /**
 2      * 继承Thread实现
 3      */
 4     public static class ThreadTest extends Thread{
 5         @Override
 6         public void run() {
 7             System.out.println(Thread.currentThread().getName());
 8         }
 9 
10         public static void main(String[] args) {
11             for (int i = 0; i <11; i++) {
12                 ThreadTest thread=new ThreadTest();
13                 thread.start();
14             }
15         }
16     }

b:

 1     /**
 2      * 实现Runnable
 3      */
 4     public static class RunnableTest implements Runnable{
 5         @Override
 6         public void run() {
 7             System.out.println(Thread.currentThread().getName());
 8         }
 9 
10         public static void main(String[] args) {
11             for (int i = 0; i <11 ; i++) {
12                 new Thread(new RunnableTest()).start();
13             }
14         }
15     }

c:此方式有返回值,可抛出异常,不过用的不多

 1  /**
 2      * 实现Callable
 3      */
 4     public static class CallableTest implements Callable<String>{
 5         @Override
 6         public String call() throws Exception {
 7             String name = Thread.currentThread().getName();
 8             return name;
10         }
11 
12         public static void main(String[] args) throws ExecutionException, InterruptedException {
13             ExecutorService es = Executors.newFixedThreadPool(10);//创建执行器,放入10个线程,执行10以后线程将从1开始计算
14             Future<String> submit = es.submit(new CallableTest());
15             System.out.println(submit.get());//获得执行结果
16             System.out.println(es.submit(new CallableTest()).get());
17             System.out.println(es.submit(new CallableTest()).get());
18             System.out.println(es.submit(new CallableTest()).get());
19             System.out.println(es.submit(new CallableTest()).get());
20             System.out.println(es.submit(new CallableTest()).get());
21             System.out.println(es.submit(new CallableTest()).get());
22             es.shutdownNow();//关闭执行器
23         }
24     }

至此,B方式是我项目中使用的最多的(不是最优的,因为我们并发不高,没什么影响,最佳的应该是使用自定义线程池),当然这只是刚刚开始,后面会继续总结并发的一系列问题

原文地址:https://www.cnblogs.com/rb2010/p/12663927.html