欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-25 15:55:57
这个问题一般会出现在面试当中,多线程创建有哪几种方式呢?答:实现Runable接口和实现Thread类。 我们先看看看实现这两种的实现方式 那么除了这两种方式以外还有什么其他方式呢? 答:可以实现Callable接口和线程池来创建线程。 ......

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

上一篇:

下一篇: