Java multi-threading (7) -JDK5 new way to create two kinds of thread

First, implement Callable Interface

Compared to using Runnable, Callable some more powerful

  • Compared run () method may return a value
  • The method can throw an exception
  • Support generic return value
  • FutureTask need the help of the class, such as access to return results

Future interfaces

  • Can cancel the results of specific Runnable, Callable tasks inquiry is complete, get the results and so on.
  • FutrueTask is the only class that implements the interface Futrue
  • FutureTask while achieving Runnable, Future interfaces. It can be executed as a thread Runnable, Callable and can get as a return value Future
class NumThread implements Callable{
    public Object call() throws Exception {
        int sum=0;
        for(int i=1;i<=100;i++){
            if(i%2==0)
            sum+=i;
        }
        return sum;
    }
}
public class newThread {
    public static void main(String[] args) {
        //创建callable接口实现类的对象
        NumThread mu=new NumThread();
        //将次callable接口实现类的对象作为传递到futureTask构造器中 创建FutureTask的对象
        FutureTask futureTask=new FutureTask(mu);
        //将FutureTask的对象作为参数传递到Thread类的构造器中 创建Thread对象 并调用start()
        new Thread(futureTask).start();
        try {
            //get()返回值即为FutureTask构造器参数callable实现类重写的call()的返回值
            Object sum=futureTask.get();
            System.out.println(sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

Second, use the thread pool

Background : frequently created and destroyed, using particularly large amounts of resources, such as threads in the concurrent case,
a great impact on performance.
idea : in advance created multiple threads into the thread pool, direct access to the use, used up
back in the pool. Avoid frequent create destruction, to achieve reuse. Similar life public transport
through the tool.
Benefits :

  • Improve the response speed (reducing the time to create a new thread)
  • Reduce resource consumption (reuse threads in the thread pool, do not need to create each time)
  • Easy to thread management
  1. corePoolSize: the size of the core pool
  2. maximumPoolSize: The maximum number of threads 
  3. keepAliveTime: After keeping up to how long the task will not terminate a thread
class NUmberThread implements Runnable{
    public void run() {
        for(int i=0;i<100;i++){
            if(i%2==0){
                System.out.println(Thread.currentThread().getName()+": "+i);
            }
        }
    }
}
class NUmberThread1 implements Runnable{
    public void run() {
        for(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) {
        //指定线程数量的线程池
        ExecutorService service = Executors.newFixedThreadPool(10);//ExecutorService是一个接口 这里返回的是接口实现类的对象
      //10为线程池的大小         
    //执行指定的线程的操作 需要提供实现runnable接口或Callable接口实现类的对象
        service.execute(new NUmberThread());//适用于Runnable
        service.execute(new NUmberThread1());//自动将线程启动
        //service.submit();//适用于Callable
        //关闭连接池
        service.shutdown();
    }
}
Published 45 original articles · won praise 43 · views 7066

Guess you like

Origin blog.csdn.net/qq_42193790/article/details/104456551