首页 > 编程语言 > 详细

多线程之创建线程有哪几种方式?

时间:2019-07-12 16:13:58      阅读:71      评论:0      收藏:0      [点我收藏+]

这个问题一般会出现在面试当中,多线程创建有哪几种方式呢?
答:实现Runable接口和实现Thread类。

我们先看看看实现这两种的实现方式

 1 package com.summer;
 2 
 3 public class ThreadA implements Runnable {
 4 
 5     public void run() {
 6         System.out.println("start ThreadA!");
 7     }
 8 
 9     public static void main(String[] args) {
10         Thread thread = new Thread(new ThreadA());
11         thread.start();
12     }
13 }

 

 1 package com.summer;
 2 
 3 public class ThreadB extends Thread {
 4 
 5     @Override
 6     public void run() {
 7         System.out.println("start ThreadB!");
 8     }
 9 
10     public static void main(String[] args) {
11         ThreadB threadB = new ThreadB();
12         threadB.start();
13     }
14 }

 

那么除了这两种方式以外还有什么其他方式呢?

答:可以实现Callable接口和线程池来创建线程。

 1 package com.summer;
 2 
 3 import java.util.concurrent.Callable;
 4 import java.util.concurrent.FutureTask;
 5 
 6 public class ThreadC implements Callable {
 7 
 8     public Object call() throws Exception {
 9         System.out.println("start ThreadC!");
10         return null;
11     }
12 
13     public static void main(String[] args) {
14         ThreadC threadC = new ThreadC();
15         FutureTask futureTask = new FutureTask(threadC);
16         Thread thread = new Thread(futureTask);
17         thread.start();
18     }
19 }

 

 1 package com.summer;
 2 
 3 import java.util.concurrent.ExecutorService;
 4 import java.util.concurrent.Executors;
 5 
 6 public class ThreadD implements Runnable {
 7 
 8     public void run() {
 9         System.out.println("start ThreadD!");
10     }
11 
12     public static void main(String[] args) {
13         ExecutorService executorService = Executors.newSingleThreadExecutor();
14         executorService.execute(new ThreadD());
15     }
16 }

多线程之创建线程有哪几种方式?

原文:https://www.cnblogs.com/tanyang/p/11176103.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!