Callable,Runnable比较及用法

编写多线程程序是为了实现多任务的并发执行,从而可以更好地与用户交互。对目前的java来讲,通常有三种方法,Thread,Runnable,Callable. java

Runnable和Callable的区别是,
(1)Callable规定的方法是call(),Runnable规定的方法是run().
(2)Callable的任务执行后可返回值,而Runnable的任务是不能返回值得
(3)call方法能够抛出异常,run方法不能够
(4)运行Callable任务能够拿到一个Future对象,表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。经过Future对象能够了解任务执行状况,可取消任务的执行,还可获取执行结果。 多线程

一、经过实现Runnable接口来建立Thread线程: 并发

  步骤1:建立实现Runnable接口的类: 异步

         
class SomeRunnable implements Runnable
{
    public void run()
    {
      //do something here
    }
} 性能

步骤2:建立一个类对象: spa

       Runnable oneRunnable = new SomeRunnable(); 线程

步骤3:由Runnable建立一个Thread对象: code

       Thread oneThread = new Thread(oneRunnable); 对象

步骤4:启动线程: blog

        oneThread.start();

至此,一个线程就建立完成了。

注释:线程的执行流程很简单,当执行代码oneThread.start();时,就会执行oneRunnable对象中的void run();方法,

该方法执行完成后,线程就消亡了。

二、与方法1相似,经过实现Callable接口来建立Thread线程:其中,Callable接口(也只有一个方法)定义以下:

public interface Callable<V>   
{   
    V call() throws Exception;   

步骤1:建立实现Callable接口的类SomeCallable<Integer>(略);

步骤2:建立一个类对象:

      Callable<Integer> oneCallable = new SomeCallable<Integer>();

步骤3:由Callable<Integer>建立一个FutureTask<Integer>对象:

      FutureTask<Integer> oneTask = new FutureTask<Integer>(oneCallable);

      注释:FutureTask<Integer>是一个包装器,它经过接受Callable<Integer>来建立,它同时实现了Future和Runnable接口。
步骤4:由FutureTask<Integer>建立一个Thread对象:

       Thread oneThread = new Thread(oneTask);

步骤5:启动线程:

       oneThread.start();

至此,一个线程就建立完成了。

三、经过继承Thread类来建立一个线程:

步骤1:定义一个继承Thread类的子类:

       

class SomeThead extends Thraad
{
    public void run()
    {
     //do something here
    }
}

步骤2:构造子类的一个对象:

      SomeThread oneThread = new SomeThread();

步骤3:启动线程:

      oneThread.start();

至此,一个线程就建立完成了。

       注释:这种建立线程的方法不够好,主要是由于其涉及运行机制问题,影响程序性能。

四、经过线程池来建立线程:

步骤1:建立线程池:

      ExecutorService pool = Executors.newCachedThreadPool();

步骤2:经过Runnable对象或Callable对象将任务提交给ExecutorService对象:

      Future<Integer> submit(Callable<Integer> task);

      注释:Future是一个接口,它的定义以下:

               
public interface Future<T>
{
    V get() throws ...;
    V get(long timeout, TimeUnit unit) throws ...;
    void cancle(boolean mayInterrupt);
    boolean isCancelled();
    boolean isDone();
}

      至此,一个线程就建立完成了。

      注释:线程池需调用shutdown();方法来关闭线程。

五、经过事件分配线程直接使用程序中的原有线程:

使用方法:
直接调用EventQueue类的静态方法invokeLater():

      EventQueue.invokeLater(oneRunnable);

      注释:调用EventQueue.invokeLater(oneRunnable);会直接执行oneRunnable对象中的run()方法


相关实例:

public class CallableFutureTest { public static void main(String[] args) throws InterruptedException, ExecutionException {  
        System.out.println("start main thread"); 
        final ExecutorService exec = Executors.newFixedThreadPool(5);  


        Callable<String> call = new Callable<String>() { public String call() throws Exception {  
                System.out.println(" start new thread.");  
                Thread.sleep(1000 * 5);  
                System.out.println(" end new thread."); // call方法返回值 
 return "some value.";  
            }  
        };  
        Future<String> task = exec.submit(call);  
        Thread.sleep(1000 * 2); // 阻塞当前线程,即主线程,并等待子线程结束  
 task.get(); 
        exec.shutdown();  
        System.out.println("end main thread");  
    }  
}
相关文章
相关标签/搜索