JDK5.0新增的创建多线程的方式:
新增一:
//创建多线程的方式三:callabe;import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;//1.创建一个Callable的实现类
class NewThread implements Callable {// 2.实现call方法(可以有返回值)@Overridepublic Object call() throws Exception {// TODO Auto-generated method stubint sum = 0;for(int i = 1 ; i <= 100 ; i++) {if(i%2 == 0) {System.out.println(i);sum+=i;}} return sum;}}public class Thread_new {public static void main(String[] args) {
// 3.创建callable的实现类的对象NewThread t1 = new NewThread();// 4.将此作为参数传递到FutureTask中的构造器中,创建FutureTask的对象FutureTask futuretask = new FutureTask (t1);// FutureTask类也实现了Runnable接口
// 5.将FutureTask的对象作为参数传递到Thread的构造器中,创建Thread对象,并且start调用new Thread(futuretask).start();try {// 6.获取callable中的返回值
// get方法的返回值即为FutureTask构造器参数中Callabl中重写的call()的返回值Object sum = futuretask.get();System.out.println(sum);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ExecutionException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
比较实现类callabe比Runnable好的原因:
1.call方法中可以有返回值
2.call方法可以抛出异常,被外面的操作捕获,并且获取异常信息
3.callabe使支持泛型的
新增方式二:线程池
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;/** 创建线程的方法四:线程池* */class ThreadFour implements Runnable{@Overridepublic void run() {// TODO Auto-generated method stubfor(int i = 0 ; i < 100 ; i++) {if(i%2==0) {System.out.println(Thread.currentThread().getName()+":"+i);}}}}//输出奇数
class ThreadFive implements Runnable{@Overridepublic void run() {// TODO Auto-generated method stubfor(int i = 0 ; i < 100 ; i++) {if(i%2!=0) {System.out.println(Thread.currentThread().getName()+":"+i);}}}}public class ThreadPool {public static void main(String[] args) {// TODO Auto-generated method stub
// 1.提供指定线程数量的线程池ExecutorService service = Executors.newFixedThreadPool(10);ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;//ThreadPoolExecutor是接口ExecutorService实现类的子类 service1.setCorePoolSize(15);
// service1.getKeepAliveTime(null);// 设置线程池的属性// service.execute(null); 适合实现Runnable类 即执行
// service.submit(null) 适合实现Callable类
// 2.执行制定的线程的操作,需要提供实现Runnable()和Callable()接口的实现类的对象service.execute(new ThreadFour());service.execute(new ThreadFive());service.shutdown();//关闭线程池 }}