JAVA并发编程>>四种实现方式

概述

1、继承Thread

2、实现Runable接口

3、实现Callable接口通过FutureTask包装器来创建Thread线程

4、通过Executor框架实现多线程的结构化,即线程池实现。(该实现方式将会下一篇单独介绍)

1、继承Thread

 1 class CreateThreadByExtendThread extends Thread {
 2     public CreateThreadByExtendThread(String name) {
 3         super(name);
 4     }
 5     @Override
 6     public void run() {
 7         for(int i=0;i<=2;i++) {
 8             System.out.println(Thread.currentThread().getName()+"线程,线程号{"+Thread.currentThread().getId()+"},i="+i);
 9         }
10     }
11 }
View Code

 2、实现Runable接口

1 class CreateThreadByImpleRunable implements Runnable{
2     @Override
3     public void run() {
4         for(int i=0;i<=2;i++) {
5             System.out.println(Thread.currentThread().getName()+"线程,线程号{"+Thread.currentThread().getId()+"},i="+i);
6         }
7     }
8     
9 }
View Code

执行CreateThreadByExtendThread和CreateThreadByImpleRunable

 1 public class CreateThread {
 2 
 3     public CreateThread() {
 4         // TODO Auto-generated constructor stub
 5     }
 6     /**
 7      * <p>
 8      * 测试并发编程实现方式
 9      * </p>
10      * @param args
11      */
12     public static void main(String[] args) {
13         CreateThreadByExtendThread ctetThread = new CreateThreadByExtendThread("AAAA");
14         ctetThread.start();
15         Thread ctbrThread = new Thread(new CreateThreadByImpleRunable(),"BBBB");
16         ctbrThread.start();
17     }
18 }
View Code

执行结果

上述是无返回结果的线程,二者区别:Thread类实现了Runable接口。从代码灵活性的角度考虑建议使用第二种方式。

3、实现Callable接口通过FutureTask包装器来创建Thread线程

 1 class CreateThreadByImpleCallable<String> implements Callable<String>{
 2     private CreateThreadByImpleCallable<String> ctbc = null;
 3     @Override
 4     public String call() throws Exception {
 5         for(int i=0;i<=2;i++) {
 6             System.out.println(Thread.currentThread().getName()+"线程,线程号{"+Thread.currentThread().getId()+"},i="+i);
 7         }
 8         return (String) "Game over";
 9     }
10     public  String getTask() throws InterruptedException, ExecutionException {
11         ctbc = ctbc == null ? new CreateThreadByImpleCallable<String>() : ctbc;
12         FutureTask<String> ftTask = new FutureTask<String>(ctbc);
13         Thread ftThread = new Thread(ftTask,"CCCC");
14         ftThread.start();
15         return ftTask.get();
16     }
17     
18 }
View Code

上述main方法添加此行代码

1 try {
2             System.out.print(new CreateThreadByImpleCallable<String>().getTask());
3         } catch (InterruptedException | ExecutionException e) {
4             // TODO Auto-generated catch block
5             e.printStackTrace();
6         }
View Code

执行结果

猜你喜欢

转载自www.cnblogs.com/zhujj1314/p/10704747.html