1 package ThreadTest; 2 3 import java.util.concurrent.Callable; 4 import java.util.concurrent.ExecutionException; 5 import java.util.concurrent.FutureTask; 6 7 public class CallableTest implements Callable { 8 @Override 9 public Object call() throws Exception { 10 int sum=0; 11 for ( int i = 0; i <=100; i++) { 12 if (i % 2 == 0) { 13 sum=sum+i; 14 System.out.println(Thread.currentThread().getName() + ":" + i); 15 } 16 } 17 return sum; 18 } 19 } 20 21 22 class Tse{ 23 public static void main(String[] args) { 24 //3:创建callable接口实现类的对象 25 CallableTest callableTest=new CallableTest(); 26 //4:将此实现类的对象作为形参传入FutureTask的构造器中,创建FutureTask的对象 27 FutureTask futureTask=new FutureTask(callableTest); 28 //5: 将FutureTask的对象作为形参传入thread类的构造器中创建thread对象 29 Thread thread=new Thread(futureTask); 30 thread.setName("线程1:"); 31 thread.start(); 32 //6:获取callable中的返回值,get返回值即为FutureTask实现类重写的call()返回值, 33 try { 34 Object sum= futureTask.get(); 35 System.out.println("总和为:"+sum); 36 } catch (InterruptedException e) { 37 e.printStackTrace(); 38 } catch (ExecutionException e) { 39 e.printStackTrace(); 40 } 41 } 42 }
对于实现Callable接口的方式与runnable接口的异同在于
1:重写实现类的run方法,pulic Object void run(){return sum} 可以有返回值
2:创建实现类的对象
3:将实现类的对象作为形参传入FutureTask的构造器中,创建FutureTask对象
4:将FutureTask的对象作为形参传入Thread类的构造器中,创建Thread类对象
5:Thread对象.start(),此时可以通过 Object sum=futuretask对象.get()得到返回值
1 package ThreadTest; 2 /** 3 * 创建线程的方法4:使用线程池 4 */ 5 6 import java.util.concurrent.*; 7 class TT implements Runnable{ 8 @Override 9 public void run() { 10 int sum = 0; 11 for (int i = 0; i <= 100; i++) { 12 if (i % 2 == 0) { 13 System.out.println(i); 14 } 15 } 16 } 17 18 } 19 20 class TT1 implements Runnable{ 21 @Override 22 public void run() { 23 int sum = 0; 24 for (int i = 0; i <= 100; i++) { 25 if (i % 2 != 0) { 26 System.out.println(i); 27 } 28 } 29 } 30 31 } 32 public class ThreadPool { 33 public static void main(String[] args) { 34 //1:提供指定线程数量的线程池 35 ExecutorService service = Executors.newFixedThreadPool(10); 36 //2:执行指定线程的操作,需要提供实现runnable接口实现类的对象 37 service.execute(new TT());//适用于runnable 38 service.execute(new TT1());//适用于runnable 39 //service.submit(); //适用于callable 40 //关闭线程池 41 service.shutdown(); 42 } 43 }
对于线程池主要的步骤:
1:提供线程池:ExecutorService service=Executors.newFixdThreadPool(线程池数量);
2:service.execute(new 实现类的对象());
3:service.shoudown 关闭线程池