Java創建線程主要有三種方式:
1、繼承Thread類
2、實現Runnable接口
3、使用Callable和Future創建線程
參考地址:https://www.cnblogs.com/yeya/p/10183366.html
一、繼承Thread類
步驟:
1、創建一個線程子類繼承Thread類
2、重寫run() 方法,把需要線程執行的程序放入run方法,線程啟動后方法里的程序就會運行
2、創建該類的實例,並調用對象的start()方法啟動線程
示例代碼如下:
1 public class ThreadDemo extends Thread{ 2 @Override 3 public void run() { 4 super.run(); 5 System.out.println("需要運行的程序。。。。。。。。"); 6 } 7 8 public static void main(String[] args) { 9 Thread thread = new ThreadDemo(); 10 thread.start(); 11 } 12 }
二、實現Runnable接口
1、定義一個線程類實現Runnable接口,並重寫該接口的run()方法,方法中依然是包含指定執行的程序。
2、創建一個Runnable實現類實例,將其作為target參數傳入,並創建Thread類實例。
3、調用Thread類實例的start()方法啟動線程。
示例代碼如下:
1 public class RunnableDemo implements Runnable{ 2 @Override 3 public void run() { 4 System.out.println("我是Runnable接口......"); 5 } 6 public static void main(String[] args) { 7 8 RunnableDemo demo = new RunnableDemo(); 9 Thread thread = new Thread(demo); 10 thread.start(); 11 } 12 }
三、使用Callable和Future創建線程
使用Callable創建線程和Runnable接口方式創建線程比較相似,不同的是,Callable接口提供了一個call() 方法作為線程執行體,而Runnable接口提供的是run()方法,同時,call()方法可以有返回值,而且需要用FutureTask類來包裝Callable對象。
1 public interface Callable<V> { 2 V call() throws Exception; 3 }
步驟:
1、創建Callable接口的實現類,實現call() 方法
2、創建Callable實現類實例,通過FutureTask類來包裝Callable對象,
該對象封裝了Callable對象的call()方法的返回值。
3、將創建的FutureTask對象作為target參數傳入,創建Thread線程實例並啟動新線程。
4、調用FutureTask對象的get方法獲取返回值。
示例代碼如下:
①.創建實現Callable接口的類
1 /** 2 *<p> Description: 使用Callable與Future創建可會獲取返回值的線程 </p> 3 *<p> Copyright: Copyright(c) 2018/12/27 </p> 4 *<p> Company: xxx </p> 5 * 6 *@author Jason 7 *@Version 1.0 2018/12/27 14:15 8 */ 9 public class ThreadUtil implements Callable { 10 11 private StudentService studentService; 12 13 public ThreadUtil() { 14 } 15 16 public ThreadUtil(StudentService studentService) { 17 this.studentService = studentService; 18 } 19 20 /** 21 * 重寫call()方法,查詢數據庫 22 * @return List<Student> 23 * @throws Exception 異常 24 */ 25 @Override 26 public List<Student> call() throws Exception { 27 List<Student> students = studentService.allStudentsList(); 28 return students; 29 } 30 }
②.測試開啟線程獲取線程返回的數據
1 /** 2 *<p> Description: 線程測試類 </p> 3 *<p> Copyright: Copyright(c) 2018/12/27 </p> 4 *<p> Company: xxx </p> 5 * 6 *@author Jason 7 *@Version 1.0 2018/12/27 14:22 8 */ 9 @RunWith(SpringJUnit4ClassRunner.class) 10 @SpringBootTest 11 public class ThreadTest 12 { 13 14 @Autowired 15 private StudentService studentService; 16 17 /** 18 * 開啟線程查詢數據庫 19 */ 20 @Test 21 public void testThread1() 22 { 23 // 1.獲取FutureTask對象 24 ThreadUtil threadUtil = new ThreadUtil(studentService); 25 FutureTask futureTask = new FutureTask(threadUtil); 26 27 // 2.開啟線程 28 new Thread(futureTask).start(); 29 30 try 31 { 32 // 3.使用Futura#get()方法獲取線程的返回值 33 List<Student> studentList = (List<Student>) futureTask.get(); 34 studentList.forEach(student -> System.out.println(student)); 35 } 36 catch (InterruptedException e) 37 { 38 e.printStackTrace(); 39 } 40 catch (ExecutionException e) 41 { 42 e.printStackTrace(); 43 } 44 } 45 }