Create a thread of execution Three ways: to achieve Callable Interface

Callable Interface

① Java 5.0 provides a new way to create a thread of execution in java.util.concurrent: Callable Interface
② Callable interface is similar to Runnable, both of which are examples of those classes may be executed by another thread design.

     Runnable but does not return results, and you can not throw checked exceptions.
③ Callable rely FutureTask, FutureTask latch can also be used

TestCallable

package com.aff.juc;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/ * 1. Create a three-way thread of execution: implement Callable interface mode Runable interface compared to the realization,
      The method may have the return value, and may run out of abnormality.
   2. Perform Callable interface mode, FutureTask required to achieve support classes for receiving the operation result.
      FutureTask is a class that implements the interface Future
   
*/
public class TestCallable {
    public static void main(String[] args) {
        TD4 ThreadDemo4 = new new ThreadDemo4 ();
         // 1. Callable execution mode, it is necessary to achieve FutureTask class support, for receiving a calculation result 
        FutureTask <Integer> = Result new new FutureTask <> (TD4);
         new new the Thread (Result) .start () ;
         // results after receiving threaded computing 2. 
        the try {
            Integer sum = result.get();
            System.out.println(sum);
            System.out.println("-----------");
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
}

/*
 * class ThreadDemo3 implements Runnable{
 * 
 * @Override public void run() { } }
 */

class ThreadDemo4 implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 0; i < 100; i++) {
            System.out.println(i);
            sum += i;
        }
        return sum;
    }
}

 

Guess you like

Origin www.cnblogs.com/afangfang/p/12631477.html