The traditional way of implementing threads is three, inheriting the thread class, overriding the run () method, implementing the Runable interface, overriding the run () method, implementing the callable interface, overriding the call () method, and documenting the most basic three encoding implementations.
First, Inherit thread
Class Extendsthread extends thread{ void run () {System.out.println ("Hello Thread"void newNew extendsthread (); Et1.start (); Et2.start ();}}
Second, realize runnable interface
PublicClass Implementsrunableimplements Runnable { public void Run () {System.out.println ("Hello Thread");} public static void main (string[] args) {implementsrunable ir1 = new implementsrunable (); Implementsrunable Ir2 = new implementsrunable (); new Thread (IR1). Start (); new Thread (IR2). Start ();}}
Third, realize callable interface
Public classImplementscallableImplementsCallable {Private intID; PublicImplementscallable (intID) { This. ID =ID; } PublicString Call ()throwsException {return"This Thread Id is:" + This. GetId (); } Public intgetId () {returnID; } Public voidSetId (intID) { This. ID =ID; } Public Static voidMain (string[] args)throwsexecutionexception, interruptedexception {executorservice es=Executors.newcachedthreadpool (); List<Future<String>> results =NewArrayList (); for(inti=1;i<=10;i++) {Results.add (Es.submit (Newimplementscallable (i))); } thread.sleep (10000); for(future<string>fs:results) { if(Fs.isdone ()) {System.out.println (Fs.get ()); } Else{System.out.println ("The Thread isn't down yet"); }} es.shutdown (); }}
Note: the Execute () method of Executorservice does not return a value, and the Submit () method has a return value of type future<t>.
Several implementations of Java multi-threading record