PackageTestA;Importjava.util.concurrent.Callable;Importjava.util.concurrent.ExecutionException;ImportJava.util.concurrent.FutureTask; Public classThreadTest { Public Static voidMain (string[] args) {//1. Inheriting the thread class NewDefinethread (). Start (); //2. Implement the Runnable interface NewThread (Newdefinerunnable ()). Start (); //3. Implement the Callable interface NewThread (Futuretask). Start (); String result= ""; Try{result=Futuretask.get (); } Catch(interruptedexception e) {e.printstacktrace (); } Catch(executionexception e) {e.printstacktrace (); } System.out.println (Result); } Static classDefinethreadextendsThread {@Override Public voidrun () { for(inti = 0; I < 100; i++) {String name2=GetName (); Try{sleep (100); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (Name2+ ": " +i); } } } Static classDefinerunnableImplementsRunnable {@Override Public voidrun () { for(inti = 0; I < 100; i++) { //String name2 = GetName ();String name = Thread.CurrentThread (). GetName ();//implements the Runnable interface, using the thread class's CurrentThread () to get the current thread object Try{Thread.CurrentThread (). Sleep (100); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (Name+ ": " +i); } } } StaticFuturetask<string> Futuretask =NewFuturetask<> (NewCallable<string>() {@Override PublicString Call ()throwsinterruptedexception {String name= ""; inti = 0; for(; i < i++;) {Name=Thread.CurrentThread (). GetName (); Thread.CurrentThread (). Sleep (100); SYSTEM.OUT.PRINTLN (Name+ ": " +i); } returnName + "----->result=" +i; } });}
1. Inherit the thread class, limiting the extensibility of the class.
2. Implement the Runnable interface, which can also implement other interfaces that can share the same target object when a new thread is opened.
// new Thread (target). Start ();
3. Implement the callable interface, the thread execution body can have a return value, and can throw an exception.
Three ways to create threads and their pros and cons