zoukankan      html  css  js  c++  java
  • java 多线程总结

    java多线程有三种实现方式。

    1,继承thread类(实际上也是实现了Runable接口)。

    2.实现Runable接口。

    3.使用ExecutorService、Callable、Future实现有返回结果的多线程。前两种都没有返结果,如果要找到返回结果需要大费周章还会漏洞百出。

    例子:

    1.继承Thread类。

    public class test extends Thread{

      //需要重写run

      public void run(){

        system.out.println("Thread go");

      }

      public static void main(String[] args){

      //生成线程需要new test(),test内部的属性不可线程之间共享。

        test t1 = new test();

        test t2 = new test();

      

        t1.start();

        t2.start();

        //如果直接调用run方法,t1.run();执行的是main函数进程,可参照Thread  Jdk源码。

      }

    }

    2.实现Runable接口

    public class test implements Runable{

      private int count=5;

      //需要重写run

      public void run(){

      for(;count>0;count--;)

        system.out.println("Thread go"+count);

      }

      public static void main(String[] args){

      //生成线程需要new test(),test内部的属性线程之间共享。

        test t1 = new test();

        //需要使用Thread类提供的方法生成线程

        Tread th1 = new Thread(t1,"线程1");

        Tread th2 = new Thread(t2,"线程2");

        th1.start();

        th2.start();

      }

    }

    3、使用ExecutorService、Callable、Future实现有返回结果的多线程
    ExecutorService、Callable、Future这个对象实际上都是属于Executor框架中的功能类。想要详细了解Executor框架的可以访问http://www.javaeye.com/topic/366591 ,这里面对该框架做了很详细的解释。返回结果的线程是在JDK1.5中引入的新特征,确实很实用,有了这种特征我就不需要再为了得到返回值而大费周折了,而且即便实现了也可能漏洞百出。
    可返回值的任务必须实现Callable接口,类似的,无返回值的任务必须Runnable接口。执行Callable任务后,可以获取一个Future的对象,在该对象上调用get就可以获取到Callable任务返回的Object了,再结合线程池接口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()方法,会阻塞直到计算完成。

    部分代码参照:http://blog.csdn.net/aboy123/article/details/38307539

  • 相关阅读:
    Kettle 实现mysql数据库不同表之间数据同步——实验过程
    Kettle ETL 来进行mysql 数据同步——试验环境搭建(表中无索引,无约束,无外键连接的情况)
    并查集知识总结
    c# 线程同步问题(about volatile)
    c# 线程的等待(堵塞)
    net中多线程返回值
    c# 中的 lock monitor mutex Semaphore 的比较
    c#两种同步结构
    links-some-blog
    T-SQL中的APPLY用法
  • 原文地址:https://www.cnblogs.com/luoluoshidafu/p/4615506.html
Copyright © 2011-2022 走看看