Java中创建线程的三种方式及其优缺点

1.自定义一个继承Thread的类,由于Java的单继承特性,限制了该类的扩展性。

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

3.实现Callable接口,重写call方法。线程执行体可以有返回值,并且可以抛出异常。

 1 import java.util.concurrent.Callable;
 2 import java.util.concurrent.ExecutionException;
 3 import java.util.concurrent.FutureTask;
 4 
 5 public class Main {
 6     public static void main(String[] args) {
 7         // 1.继承Thread类
 8         new DefineThread().start();
 9         // 2.实现Runnable接口
10         new Thread(new DefineRunnable()).start();
11         // 3.实现Callable接口
12         new Thread(futureTask).start();
13         String result = "";
14         try {
15             result = futureTask.get();
16         } catch (InterruptedException e) {
17             e.printStackTrace();
18         } catch (ExecutionException e) {
19             //ExecutionException封装了call()方法抛出的异常
20             e.printStackTrace();
21             e.getCause();
22             //getCause()方法把被包装的原始异常提取出来
23         }
24         System.out.println(result);
25     }
26 
27     static class DefineThread extends Thread {
28 
29         @Override
30         public void run() {
31             for (int i = 0; i < 100; i++) {
32                 String name2 = getName();
33                 try {
34                     sleep(100);
35                 } catch (InterruptedException e) {
36                     e.printStackTrace();
37                 }
38                 System.out.println(name2 + ": " + i);
39             }
40         }
41     }
42 
43     static class DefineRunnable implements Runnable {
44 
45         @Override
46         public void run() {
47             for (int i = 0; i < 100; i++) {
48                 // String name2 = getName();
49                 String name = Thread.currentThread().getName(); // 实现runnable接口,使用Thread类的currentThread()获取当前线程对象
50                 try {
51                     Thread.currentThread().sleep(100);
52                 } catch (InterruptedException e) {
53                     e.printStackTrace();
54                 }
55                 System.out.println(name + ": " + i);
56             }
57         }
58     }
59 
60     static FutureTask<String> futureTask = new FutureTask<>(new Callable<String>() {
61 
62         @Override
63         public String call() throws InterruptedException {
64             String name = "";
65             int i = 0;
66             for (; i < 100; i++) {
67                 name = Thread.currentThread().getName();
68                 Thread.currentThread().sleep(100);
69                 System.out.println(name + ": " + i);
70             }
71             return name + " ----->Result=" + i;
72         }
73     });
74 }

 

posted @ 2017-10-30 18:36  永恒之光  阅读(427)  评论(0编辑  收藏  举报