Callable (simple)

Time:2021-9-19

1. Can have return value
2. Exceptions can be thrown
3. Different methods, run() / call()

Callable (simple)

Callable (simple)

Callable (simple)

Code test

package com.hudu.demo01.callable;

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

public class CallableTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        new Thread(new MyThread()).start();  Class implements the runnable () interface

//        new Thread(new Runnable()).start();
//        new Thread(new FutureTask<V>()).start();// Equivalent to the above, futuretask is the implementation class of runnable
//        new Thread(new FutureTask<V>(Callable)).start();// Futuretask is another construction method. The parameter is to pass in a callable

//        new Thread().start();// How do I start callable
        MyThread thread = new MyThread();
        //Adaptation class
        FutureTask futureTask = new FutureTask(thread);
        new Thread(futureTask,"A").start();
        new Thread(futureTask,"B").start();// The results will be cached to improve efficiency
        Integer o = (Integer)futureTask.get();// Get the return result of callable. This get method will block! Put it last
        //Or use asynchronous communication processing
        System.out.println(o);
    }
}

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

class MyThread implements Callable<Integer> {


    @Override
    public Integer call() throws Exception {
        System.out.println("call()");// Several calls will be printed
        return 12345;
    }
}

Details:
1. With cache
2. The result may need to wait and block

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Recommended Today

Seven Python code review tools recommended

althoughPythonLanguage is one of the most flexible development languages at present, but developers often abuse its flexibility and even violate relevant standards. So PythoncodeThe following common quality problems often occur: Some unused modules have been imported Function is missing arguments in various calls The appropriate format indentation is missing Missing appropriate spaces before and after […]