java创建多线程的三种方法

最近复习到java多线程的创建,在实际应用中会经常使用到,所以结合了其他的博客,写了这篇总结。
参考的博客原地址为:http://www.cnblogs.com/felixzh/p/6036074.html

1. extends Thread类,创建线程
Thread类本质上是实现了Runnable接口的一个实例,代表一个线程的实例。启动线程的唯一方法就是通过Thread类的start()实例方法。start()方法是一个native方法,它将启动一个新线程,并执行run()方法。这种方式实现多线程很简单,通过自己的类直接extend Thread,并复写run()方法,就可以启动新线程并执行自己定义的run()方法。

public class threadCode extends Thread{
     public void run(){
         System.out.println("My thread.run()");
     }
     public static void main(String[] args){
         threadCode thread1 = new threadCode();
         threadCode thread2 = new threadCode();
         thread1.start();
         thread2.start();
    }
}

运行结果:
My thread.run()
My thread.run()

2. implements Runnable接口

  • 如果自己的类已经extends另一个类,就无法直接extends Thread,此时,可以实现一个Runnable接口.
  • 为了启动MyThread,需要首先实例化一个Thread,并传入自己的MyThread实例
  • 事实上,当传入一个Runnable target参数给Thread后,Thread的run()方法就会调用target.run(),参考JDK源代码
  • public void run() {
      if (target != null) {
       target.run();
      }
    }
public class threadCode extends otherClass implements Runnable{
     public void run(){
         System.out.println("My thread.run()");
     }
     public static void main(String[] args){
         threadCode thread1 = new threadCode();
         threadCode thread2 = new threadCode();
         Thread thread3 = new Thread(thread1);
         Thread thread4 = new Thread(thread2);
         thread3.start();
         thread4.start();
     }
}

运行结果:
My thread.run()
My thread.run()

由于java的单继承多实现的特性,在不同的情况选择使用继承或者是实现接口的方式。

3. implements Callable接口,通过FutureTask包装器来创建Thread线程

  • ExecutorService、Callable、Future这个对象实际上都是属于Executor框架中的功能类。想要详细了解Executor框架的可以访问http://www.javaeye.com/topic/366591 ,这里面对该框架做了很详细的解释。返回结果的线程是在JDK1.5中引入的新特征,确实很实用,有了这种特征我就不需要再为了得到返回值而大费周折了,而且即便实现了也可能漏洞百出。
  • 可返回值的任务必须实现Callable接口,类似的,无返回值的任务必须Runnable接口。
  • 执行Callable任务后,可以获取一个Future的对象,在该对象上调用get就可以获取到Callable任务返回的Object了,再结合线程池接口ExecutorService就可以实现传说中有返回结果的多线程了。
  • 注意:get方法是阻塞的,即:线程无返回结果,get方法会一直等待。
  • ExecutoreService提供了submit()方法,传递一个Callable,或Runnable,返回Future。如果Executor后台线程池还没有完成Callable的计算,这调用返回Future对象的get()方法,会阻塞直到计算完成。
  • 下面提供了一个完整的有返回结果的多线程测试例子,在JDK1.8下验证过没问题可以直接使用。代码如下:
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

/**
 * Created by user on 2017/8/24.
 */
public class Main{
    public static void main(String[] args)throws ExecutionException,InterruptedException{
        System.out.println("---------start-------------");
        Date date1 = new Date();
        int taskSize = 5;
        //create a thread pool
        ExecutorService pool = Executors.newFixedThreadPool(taskSize);
        List<Future> list = new ArrayList<Future>();
        //创建多个有返回值的任务,这里创建了5个任务
        for(int i=0;i<taskSize;i++){
            Callable c  = new MyCallable(i+"");
            //执行任务,并获取Future对象,保存到list中;
            Future f = pool.submit(c);
            list.add(f);
        }
        //close pool
        pool.shutdown();
        //获取所有并发任务的运行结果
        for(Future f:list){
            //从future对象获取任务返回值,使用Future.get()方法。
            System.out.println(f.get().toString());
        }
        Date date2 = new Date();
        System.out.println("---------------finished--------------,"+" run time is: "+(date2.getTime()-date1.getTime()));

    }
    //创建具有任务返回值的线程,实现Callable接口。
    public static class MyCallable implements Callable<Object>{
        private String taskNum;
        MyCallable(String num){
            this.taskNum = num;
        }
        public Object call()throws Exception{
            System.out.println(" "+taskNum+" is started");
            Date d1 = new Date();
            Thread.sleep(1000);
            Date d2 = new Date();
            long t = d2.getTime() - d1.getTime();
            System.out.println(" "+taskNum+" is finished");
            return taskNum+" used time is "+t;
        }


    }
}

运行结果:
———start————-
0 is started
2 is started
1 is started
3 is started
4 is started
0 is finished
3 is finished
4 is finished
0 used time is 1001
1 is finished
1 used time is 1008
2 is finished
2 used time is 1009
3 used time is 1003
4 used time is 1003
—————finished————–, run time is: 1035

说明:
代码说明:
上述代码中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类。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值