欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JAVA中实现多线程的四种方式

程序员文章站 2022-07-02 14:26:47
Java中多线程实现方式主要有四种:1>继承Thread类、2>实现Runnable接口、3>实现Callable接口通过FutureTask包装器来创建Thread线程、4>使用ExecutorService、Callable、Future实现有返回结果的多线程。 其中前两种方式线程执行完后都没有 ......

java中多线程实现方式主要有四种:1>继承thread类、2>实现runnable接口、3>实现callable接口通过futuretask包装器来创建thread线程、4>使用executorservice、callable、future实现有返回结果的多线程。

其中前两种方式线程执行完后都没有返回值,后两种是带返回值的。

 

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

public class mythread extends thread {  
  public void run() {  
   system.out.println("mythread.run()");  
  } 

     public static void main(string[] args)
     {

       mythread mythread1 = new mythread();  
       mythread mythread2 = new mythread();  
       mythread1.start();  
       mythread2.start();  

}
}  
 

2、实现runnable接口创建线程
如果自己的类已经extends另一个类,就无法直接extends thread,此时,可以实现一个runnable接口,如下:

public class mythread extends otherclass implements runnable {  
  public void run() {  
   system.out.println("mythread.run()");  
  }  
}  

为了启动mythread,需要首先实例化一个thread,并传入自己的mythread实例:

mythread mythread = new mythread();  
thread thread = new thread(mythread);  
thread.start();  

事实上,当传入一个runnable target参数给thread后,thread的run()方法就会调用target.run(),参考jdk源代码:

public void run() {  
  if (target != null) {  
   target.run();  
  }  
}  

3、实现callable接口通过futuretask包装器来创建thread线程

callable接口(也只有一个方法)定义如下:   

public interface callable<v>   { 
  v call() throws exception;   } 
public class somecallable<v> extends otherclass implements callable<v> {

    @override
    public v call() throws exception {
        // todo auto-generated method stub
        return null;
    }

}
callable<v> onecallable = new somecallable<v>();   
//由callable<integer>创建一个futuretask<integer>对象:   
futuretask<v> onetask = new futuretask<v>(onecallable);   
//注释:futuretask<integer>是一个包装器,它通过接受callable<integer>来创建,它同时实现了future和runnable接口。 
  //由futuretask<integer>创建一个thread对象:   
thread onethread = new thread(onetask);   
onethread.start();   
//至此,一个线程就创建完成了。

4、使用executorservice、callable、future实现有返回结果的线程

executorservice、callable、future三个接口实际上都是属于executor框架。返回结果的线程是在jdk1.5中引入的新特征,有了这种特征就不需要再为了得到返回值而大费周折了。而且自己实现了也可能漏洞百出。

可返回值的任务必须实现callable接口。类似的,无返回值的任务必须实现runnable接口。

执行callable任务后,可以获取一个future的对象,在该对象上调用get就可以获取到callable任务返回的object了。

注意:get方法是阻塞的,即:线程无返回结果,get方法会一直等待。

再结合线程池接口executorservice就可以实现传说中有返回结果的多线程了。

下面提供了一个完整的有返回结果的多线程测试例子,在jdk1.5下验证过没问题可以直接使用。代码如下:

import java.util.concurrent.*;  
import java.util.date;  
import java.util.list;  
import java.util.arraylist;  
  
/** 
* 有返回值的线程 
*/  
@suppresswarnings("unchecked")  
public class test {  
public static void main(string[] args) throws executionexception,  
   interruptedexception {  
   system.out.println("----程序开始运行----");  
   date date1 = new date();  
  
   int tasksize = 5;  
   // 创建一个线程池  
   executorservice pool = executors.newfixedthreadpool(tasksize);  
   // 创建多个有返回值的任务  
   list<future> list = new arraylist<future>();  
   for (int i = 0; i < tasksize; i++) {  
    callable c = new mycallable(i + " ");  
    // 执行任务并获取future对象  
    future f = pool.submit(c);  
    // system.out.println(">>>" + f.get().tostring());  
    list.add(f);  
   }  
   // 关闭线程池  
   pool.shutdown();  
  
   // 获取所有并发任务的运行结果  
   for (future f : list) {  
    // 从future对象上获取任务的返回值,并输出到控制台  
    system.out.println(">>>" + f.get().tostring());  
   }  
  
   date date2 = new date();  
   system.out.println("----程序结束运行----,程序运行时间【"  
     + (date2.gettime() - date1.gettime()) + "毫秒】");  
}  
}  
  
class mycallable implements callable<object> {  
private string tasknum;  
  
mycallable(string tasknum) {  
   this.tasknum = tasknum;  
}  
  
public object call() throws exception {  
   system.out.println(">>>" + tasknum + "任务启动");  
   date datetmp1 = new date();  
   thread.sleep(1000);  
   date datetmp2 = new date();  
   long time = datetmp2.gettime() - datetmp1.gettime();  
   system.out.println(">>>" + tasknum + "任务终止");  
   return tasknum + "任务返回运行结果,当前任务时间【" + time + "毫秒】";  
}  
}  

 

代码说明:
上述代码中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()方法,会阻塞直到计算完成。