多線程之創建線程有哪幾種方式?


這個問題一般會出現在面試當中,多線程創建有哪幾種方式呢?
答:實現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 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM