There are three ways to create a Thread. The first two are to inherit the Thread class and implement the Runnable interface. This time we will talk about the third Callable interface. First, compare the Runnable interface with the Callable interface
/ / the Runnable interface
class MyThreadRunnable implements Runnable {
@Override
public void run(a) {}}//Callable
class MyThreadCallable implements Callable<Integer> {
@Override
public Integer call(a) throws Exception {
System.out.println("come in here");
return 1024; }}Copy the code
As you can see, the Callable interface has generics and methods have return values, which is an enhancement to the older technique because of the presence of return values, thus increasing thread granularity.
How to create a Callable thread
- If you create a thread directly and pass in a class that implements the Callable interface, you will get an error
The reason is that Thread does not have a Callable constructor
Here we borrow another class, FutureTask, which implements the RunnableFuture interface and inherits the Runnable interface. The constructor of this class just needs to pass in the implementation class of the Callable interface.
FutureTask implements the RunnableFuture interface, which inherits the Runnable interface, and in the FutureTask constructor, Callable can be passed in
So, the way we create threads is as follows
Therefore, the thread is created as follows
- The resource class
class MyThread implements Callable<Integer>{
@Override
public Integer call(a) throws Exception {
System.out.println(Thread.currentThread().getName()+"Entered the Callable");
TimeUnit.SECONDS.sleep(3);
/ / the return value
return 1024; }}Copy the code
- The main method
public class _The third way to create a threadCallableinterface{
public static void main(String[] args) throws ExecutionException, InterruptedException {
// Thread thread = new Thread(MyThread);
FutureTask futureTask = new FutureTask(new MyThread());
new Thread(futureTask,"AA").start();
// The get method gets the return valueSystem.out.println(futureTask.get()); }}Copy the code
The startup runs normally and returns a value
There are two points to note
- The get() method blocks and is usually placed last, otherwise it will block the thread
- If there are two threads using the same instance, it will only execute once, because a futureTask, no matter how many threads call it, will call the same futureTask object. The same FutureTask instance is reused in multiple threads only once