当前位置: 移动技术网 > IT编程>开发语言>Java > 多线程之创建线程有哪几种方式?

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

2019年07月12日  | 移动技术网IT编程  | 我要评论

这个问题一般会出现在面试当中,多线程创建有哪几种方式呢?
答:实现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 }

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网