创建线程的三种方式

一、继承Thread类

java中类是单继承的,继承了该类就无法继承其他类,增加了代码的耦合度,现在提倡的是面向接口编程。

二、实现Runnable接口

相比与方式一,使用实现接口来实现,降低了程序间的耦合度,缺点是没有返回值。

三、实现Callable接口,将Callable实例传给FutureTask(FutureTask实现了RunnableFuture接口,RunnableFuture继承了Runnable接口

和方式二一样也是通过实现接口来创建线程,不同的是可以有返回值。

代码:

 1 package com.shamgod.thread;
 2 
 3 import java.util.concurrent.Callable;
 4 import java.util.concurrent.ExecutionException;
 5 import java.util.concurrent.ExecutorService;
 6 import java.util.concurrent.Executors;
 7 import java.util.concurrent.Future;
 8 import java.util.concurrent.FutureTask;
 9 
10 /**
11  * 创建线程的三种方式
12  * @author ShammGod
13  *
14  */
15 public class TestThread {
16     
17     public static void main(String[] args) throws InterruptedException, ExecutionException {
18         //继承Thread类
19         Thread t1 = new Thread1();
20         t1.start();
21         
22         //实现Runnable接口,将该实例作为参数创建Thread对象
23         Runnable runnable = new Thread2();
24         Thread t2 = new Thread(runnable);
25         t2.start();
26         
27         //实现Callable接口,将该实例作为参数创建FutureTask对象,将FutureTask对象作为参数创建Thread对象
28         Callable callable = new Thread3();
29         FutureTask<String> futureTask = new FutureTask<>(callable);
30         Thread t3 = new Thread(futureTask);
31         t3.start();
32         futureTask.get();//call方法的返回值
33         
34         //实现Callable接口,将该实例传给线程池的submit方法启动线程
35         ExecutorService threadPool = Executors.newCachedThreadPool();
36         Callable<String> task = new Thread3();
37         Future<String> future = threadPool.submit(task);
38         threadPool.shutdown();
39         future.get();//call方法的返回值
40 
41     }
42 }
43 /**
44  * 1、继承Thread
45  * @author ShammGod
46  *
47  */
48 class Thread1 extends Thread{
49     @Override
50     public void run() {
51         System.out.println("我是继承Thread创建的线程:" + Thread.currentThread().getName());
52     }
53 }
54 
55 /**
56  * 2、实现Runnable接口
57  * @author ShammGod
58  *
59  */
60 class Thread2 implements Runnable{
61 
62     @Override
63     public void run() {
64         // TODO Auto-generated method stub
65             System.out.println("我是实现Runnable接口创建的线程:"+Thread.currentThread().getName());
66     }
67 }
68 
69 /**
70  * 3、实现Callable接口
71  * @author ShammGod
72  *
73  */
74 class Thread3 implements Callable<String>{
75 
76     @Override
77     public String call() throws Exception {
78         System.out.println("我是实现Callable接口创建的线程:"+Thread.currentThread().getName());
79         return "返回值";
80     }
81     
82 }

 

转载于:https://www.cnblogs.com/qihaixing/p/9324012.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值