Java多线程实现的方式有四种
1.继承Thread类,重写run方法
2.实现Runnable接口,重写run方法,实现Runnable接口的实现类的实例对象作为Thread构造函数的target
3.通过Callable和FutureTask创建线程
4.通过线程池创建线程
前面两种可以归结为一类:无返回值,原因很简单,通过重写run方法,run方式的返回值是void,所以没有办法返回结果。
后面两种可以归结成一类:有返回值,通过Callable接口,就要实现call方法,这个方法的返回值是Object,所以返回的结果可以放在Object对象中。
第一种:继承Thread类,重写该类的run()方法。
1 class MyThread extends Thread { 2 3 private int i = 0; 4 5 @Override 6 public void run() { 7 for (i = 0; i < 100; i++) { 8 System.out.println(Thread.currentThread().getName() + " " + i); 9 } 10 } 11 }
1 public class ThreadTest { 2 3 public static void main(String[] args) { 4 for (int i = 0; i < 100; i++) { 5 System.out.println(Thread.currentThread().getName() + " " + i); 6 if (i == 30) { 7 Thread myThread1 = new MyThread(); // 创建一个新的线程 myThread1 此线程进入新建状态 8 Thread myThread2 = new MyThread(); // 创建一个新的线程 myThread2 此线程进入新建状态 9 myThread1.start(); // 调用start()方法使得线程进入就绪状态 10 myThread2.start(); // 调用start()方法使得线程进入就绪状态 11 } 12 } 13 } 14 }
如上所示,继承Thread类,通过重写run()方法定义了一个新的线程类MyThread,其中run()方法的方法体代表了线程需要完成的任务,称之为线程执行体。当创建此线程类对象时一个新的线程得以创建,并进入到线程新建状态。通过调用线程对象引用的start()方法,使得该线程进入到就绪状态,此时此线程并不一定会马上得以执行,这取决于CPU调度时机。
第二种:实现Runnable接口,并重写该接口的run()方法。
创建Runnable实现类的实例,并以此实例作为Thread类的target来创建Thread对象,该Thread对象才是真正的线程对象。
1 class MyRunnable implements Runnable { 2 private int i = 0; 3 4 @Override 5 public void run() { 6 for (i = 0; i < 100; i++) { 7 System.out.println(Thread.currentThread().getName() + " " + i); 8 } 9 } 10 }
1 public class ThreadTest { 2 3 public static void main(String[] args) { 4 for (int i = 0; i < 100; i++) { 5 System.out.println(Thread.currentThread().getName() + " " + i); 6 if (i == 30) { 7 Runnable myRunnable = new MyRunnable(); // 创建一个Runnable实现类的对象 8 Thread thread1 = new Thread(myRunnable); // 将myRunnable作为Thread target创建新的线程 9 Thread thread2 = new Thread(myRunnable); 10 thread1.start(); // 调用start()方法使得线程进入就绪状态 11 thread2.start(); 12 } 13 } 14 } 15 }
第三种:使用Callable和Future接口创建线程。
a:创建Callable接口的实现类 ,并实现Call方法
b:创建Callable实现类的实现,使用FutureTask类包装Callable对象,该FutureTask对象封装了Callable对象的Call方法的返回值
c:使用FutureTask对象作为Thread对象的target创建并启动线程
d:调用FutureTask对象的get()来获取子线程执行结束的返回值
1 public class ThreadTest { 2 3 public static void main(String[] args) { 4 5 Callable<Integer> myCallable = new MyCallable(); // 创建MyCallable对象 6 FutureTask<Integer> ft = new FutureTask<Integer>(myCallable); //使用FutureTask来包装MyCallable对象 7 8 for (int i = 0; i < 100; i++) { 9 System.out.println(Thread.currentThread().getName() + " " + i); 10 if (i == 30) { 11 Thread thread = new Thread(ft); //FutureTask对象作为Thread对象的target创建新的线程 12 thread.start(); //线程进入到就绪状态 13 } 14 } 15 16 System.out.println("主线程for循环执行完毕.."); 17 18 try { 19 int sum = ft.get(); //取得新创建的新线程中的call()方法返回的结果 20 System.out.println("sum = " + sum); 21 } catch (InterruptedException e) { 22 e.printStackTrace(); 23 } catch (ExecutionException e) { 24 e.printStackTrace(); 25 } 26 27 } 28 } 29 30 31 class MyCallable implements Callable<Integer> { 32 private int i = 0; 33 34 // 与run()方法不同的是,call()方法具有返回值 35 @Override 36 public Integer call() { 37 int sum = 0; 38 for (; i < 100; i++) { 39 System.out.println(Thread.currentThread().getName() + " " + i); 40 sum += i; 41 } 42 return sum; 43 } 44 45 }
首先,我们发现,在实现Callable接口中,此时不再是run()方法了,而是call()方法,此call()方法作为线程执行体,同时还具有返回值!在创建新的线程时,是通过FutureTask来包装MyCallable对象,同时作为了Thread对象的target。
第四种:通过线程池创建线程。
1 public class ThreadDemo05{ 2 private static int POOL_NUM = 10; //线程池数量 3 /** 4 * @param args 5 * @throws InterruptedException 6 */ 7 public static void main(String[] args) throws InterruptedException { 8 // TODO Auto-generated method stub 9 ExecutorService executorService = Executors.newFixedThreadPool(5); 10 for(int i = 0; i<POOL_NUM; i++) { 11 RunnableThread thread = new RunnableThread(); 12 //Thread.sleep(1000); 13 executorService.execute(thread); 14 } 15 //关闭线程池 16 executorService.shutdown(); 17 } 18 } 19 20 class RunnableThread implements Runnable { 21 @Override 22 public void run() { 23 System.out.println("通过线程池方式创建的线程:" + Thread.currentThread().getName() + " "); 24 } 25 }
ExecutorService、Callable都是属于Executor框架。返回结果的线程是在JDK1.5中引入的新特征,还有Future接口也是属于这个框架,有了这种特征得到返回值就很方便了。
通过分析可以知道,他同样也是实现了Callable接口,实现了Call方法,所以有返回值。这也就是正好符合了前面所说的两种分类
执行Callable任务后,可以获取一个Future的对象,在该对象上调用get就可以获取到Callable任务返回的Object了。get方法是阻塞的,即:线程无返回结果,get方法会一直等待。
再介绍Executors类:提供了一系列工厂方法用于创建线程池,返回的线程池都实现了ExecutorService接口。
public static ExecutorService newFixedThreadPool(int nThreads)
创建固定数目线程的线程池。
public static ExecutorService newCachedThreadPool()
创建一个可缓存的线程池,调用execute 将重用以前构造的线程(如果线程可用)。如果现有线程没有可用的,则创建一个新线程并添加到池中。终止并从缓存中移除那些已有 60 秒钟未被使用的线程。
public static ExecutorService newSingleThreadExecutor()
创建一个单线程化的Executor。
public static ScheduledExecutorService newScheduledThreadPool(int
corePoolSize)
创建一个支持定时及周期性的任务执行的线程池,多数情况下可用来替代Timer类。
ExecutoreService提供了submit()方法,传递一个Callable,或Runnable,返回Future。如果Executor后台线程池还没有完成Callable的计算,这调用返回Future对象的get()方法,会阻塞直到计算完成。
参考:https://www.cnblogs.com/lwbqqyumidi/p/3804883.html
https://blog.csdn.net/u011480603/article/details/75332435/