Third way to create a thread--using the callable interface

Source: Internet
Author: User

Callable is an interface similar to runnable, where classes that implement callable and classes that implement runnable are tasks that can be performed by other threads.

Pros: There are return values

Cons: Implementing tedious

Simple implementation:

Callableandfuture.java
/*** Simple Implementation * *@author: Liuqi * @date: 2018-06-13 11:10.*/ Public classCallableandfuture {Static classMyThreadImplementsCallable<string>{@Override PublicString Call ()throwsException {return"Hello World"; }    }     Public Static voidMain (string[] args) {Executorservice ThreadPool=Executors.newsinglethreadexecutor (); Future<String> future = Threadpool.submit (NewMyThread ()); Try{System.out.println (Future.get ()); } Catch(Exception e) {}finally{threadpool.shutdown (); }    }}

Operation Result:

Hello World

Advanced:

Race.java
/*** Implement callable class * *@author: Liuqi * @date: 2018-06-13 10:13.*/ Public classRaceImplementsCallable<integer> {    PrivateString name; Private LongTime ; Private BooleanFlag =true; //Number of steps    Private intStep = 0;  PublicRace () {} PublicRace (String name,intTime ) {        Super();  This. Name =name;  This. Time =Time ; } @Override PublicInteger Call ()throwsException { while(flag) {Thread.Sleep (time); Step++; }        returnstep; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public LongGetTime () {returnTime ; }     Public voidSetTime (LongTime ) {         This. Time =Time ; }     Public BooleanIsflag () {returnFlag; }     Public voidSetflag (Booleanflag) {         This. Flag =Flag; }     Public intGetstep () {returnstep; }     Public voidSetStep (intStep) {         This. Step =step; }}
Demo05.java
/*** Create thread with collable interface * *@author: Liuqi * @date: 2018-06-13 10:22.*/ Public classDemo05 { Public Static voidMain (string[] args)throwsinterruptedexception,executionexception {//Create two threadsExecutorservice ser = Executors.newfixedthreadpool (2); Race Tortoise=NewRace ("Turtle", 1000); Race Rabbit=NewRace ("Rabbit", 500); //Get Future Objectsfuture<integer> RESULT1 =Ser.submit (Tortoise); Future<Integer> RESULT2 =ser.submit (rabbit); //2 secondsThread.Sleep (2000); //Stop thread Body loopingTortoise.setflag (false); Rabbit.setflag (false); //Get Value        intNUM1 =Result1.get (); intnum2 =Result2.get (); System.out.println ("Turtle ran" + num1 + "Step"); System.out.println ("Rabbit ran" + num2 + "Step"); //Stop ServiceSer.shutdownnow (); }}

Operation Result:

The turtle ran 3 paces.
The rabbit ran 5 paces.

Code Address: Https://github.com/yuki9467/TST-javademo/tree/master/src/main/thread

There are several differences between callable and runnable:

The 1.Callable method is call (), and runnable specifies the method is run ();

2.Callable a task can return a value after execution, and runnable cannot return a value;

3.call () throws an exception, and run () cannot throw an exception;

4. Run the callable task to get a future object, the future represents the result of an asynchronous calculation, through the future object to understand the task execution, can cancel the execution of the task, but also get the result of the task execution.

The third way to create a thread--using the callable interface

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.