1, not clear to see the blog http://www.cnblogs.com/dolphin0520/p/3949310.html
We use the code above to make a turtle-rabbit race.
Packagecom.weiyuan.test;Importjava.util.concurrent.Callable;ImportJava.util.concurrent.Executor;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.Future; Public classMain { Public Static voidMain (string[] args)throwsException {//TODO auto-generated Method Stub intCounttime = 4000;//total time for runningExecutorservice service = Executors.newfixedthreadpool (2); Task Tuzi=NewTask ("Rabbit", 500); Task Wugui=NewTask ("Turtle", 1000); Future<Integer> Rst1 =Service.submit (Tuzi); Future<Integer> Rst2 =Service.submit (Wugui); /*** The total length of the run is 4 seconds **/Thread.Sleep (counttime); /** Running time is up, remember to quit the thread **/Tuzi.setflag (false); Wugui.setflag (false); Integer NUM1=Rst1.get (); Integer num2=Rst2.get (); System.out.println ("Rabbit" + "Run" +num1+ "step"); System.out.println ("Turtle" + "Run" +num2+ "step"); /*** Close thread pool **/Service.shutdown (); } Public Static classTaskImplementsCallable<integer>{ /*** Rabbits or turtles * time rabbits and turtles run times * Running time is big stop thread exit * Number of steps to run **/ PrivateString name; Private LongTime ; Private BooleanFlag =true; Private intStep = 0; PublicTask (String name,LongTime ) { This. Name =name; This. Time =Time ; } @Override PublicInteger Call ()throwsException {//TODO auto-generated Method Stub 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; } }}
The running result of the program is:
The rabbit ran 9 paces.
The turtle ran 5 paces.
Java Concurrency Programming: callable, Future, and futuretask for turtle and rabbit races