创建线程的四种方式

(1)继承Thread类

(2)实现Runnable接口

(3)实现Callable接口

(4)使用线程池

 1 package com.example.concurrency;
 2 
 3 import java.util.concurrent.Callable;
 4 import java.util.concurrent.ExecutionException;
 5 import java.util.concurrent.Executor;
 6 import java.util.concurrent.ExecutorService;
 7 import java.util.concurrent.Executors;
 8 import java.util.concurrent.Future;
 9 import java.util.concurrent.FutureTask;
10 //第一种:继承Thread类
11 class MyThread extends Thread {
12     public void run() {
13         System.out.println("线程调用");
14     }
15 }
16 
17 //第二种,实现Runnable接口
18 class MyRunnable implements Runnable {
19     private Boolean tag = true;
20 
21     @Override
22     public void run() {
23         // TODO Auto-generated method stub
24         int i = 0;
25         while (tag) {
26             System.out.println("线程调用:" + i++);
27         }
28     }
29 
30     public void stop() {
31         this.tag = false;
32     }
33 }
34 
35 //第三种:实现Callable接口
36 class MyCallable implements Callable<Integer> {
37 
38     @Override
39     public Integer call() throws Exception {
40         // TODO Auto-generated method stub
41         System.out.println("线程调用,返回123");
42         return 123;
43     }
44 
45 }
46 
47 //创建线程的四种方式
48 public class demo05 {
49 
50     public static void main(String[] args) throws InterruptedException, ExecutionException {
51         // 方式一:继承Thread类
52         MyThread thread3 = new MyThread();
53         thread3.start();
54 
55         // 方式二:实现Runnable接口
56         MyRunnable instance = new MyRunnable();
57         Thread thread = new Thread(instance);
58         thread.start();
59 
60         // 方式三-实现Callable接口:
61         MyCallable mc = new MyCallable();
62         FutureTask<Integer> ft = new FutureTask<Integer>(mc);
63         Thread thread2 = new Thread(ft);
64         thread2.start();
65 
66         // 方式四-使用线程池:
67         ExecutorService ser = Executors.newFixedThreadPool(1);// 线程池
68         Future<Integer> ft2 = ser.submit(mc);// 执行线程
69         Integer result = ft2.get();// 获取结果
70         ser.shutdown();// 关闭
71     }
72 }

 

posted on 2021-11-17 16:59  Sempron2800+  阅读(38)  评论(0编辑  收藏  举报