1.Thread
/** * */ PackageTestjava2.thread;/** * @authorXXX.SJTU * @function * @date May 17, 2017 *@version */ Public classFirstthreadtestextendsThread {inti = 0; PublicFirstthreadtest (inti) {Super(); This. i =i; } Publicfirstthreadtest () {Super(); //TODO auto-generated Constructor stub } Publicfirstthreadtest (Runnable target, String name) {Super(target, name); //TODO auto-generated Constructor stub } Publicfirstthreadtest (Runnable target) {Super(target); //TODO auto-generated Constructor stub } Publicfirstthreadtest (String name) {Super(name); //TODO auto-generated Constructor stub } Publicfirstthreadtest (threadgroup Group, Runnable Target, String name,LongstackSize) { Super(group, target, name, stackSize); //TODO auto-generated Constructor stub } Publicfirstthreadtest (threadgroup Group, Runnable Target, String name) {Super(group, target, name); //TODO auto-generated Constructor stub } Publicfirstthreadtest (threadgroup Group, Runnable target) {Super(group, target); //TODO auto-generated Constructor stub } Publicfirstthreadtest (threadgroup Group, String name) {Super(group, name); //TODO auto-generated Constructor stub } //rewrite the Run method, the method body of the Run method is the field execution body Public voidrun () {//Current thread: thisSystem.out.println ( This. GetName () + "" +i); } Public Static voidMain (string[] args) {System.out.println (Thread.CurrentThread (). GetName ()); NewFirstthreadtest (888). Start (); }}
2.Runnable
/** * */ PackageTestjava2.thread;/** * @authorXXX.SJTU * @function * @date May 17, 2017 *@version */ Public classRunnablethreadtestImplementsRunnable {Private inti; Publicrunnablethreadtest () {Super(); //TODO auto-generated Constructor stub } PublicRunnablethreadtest (inti) {Super(); This. i =i; } @Override Public voidrun () {//Current thread: Thread.CurrentThread ()System.out.println (Thread.CurrentThread (). GetName () + "" +i); } Public Static voidMain (string[] args) {System.out.println (Thread.CurrentThread (). GetName ()); Runnablethreadtest RTT=NewRunnablethreadtest (999); NewThread (RTT, "New Thread 1"). Start (); }}
3.Callable
/** * */ PackageTestjava2.thread;Importjava.util.concurrent.Callable;Importjava.util.concurrent.ExecutionException;ImportJava.util.concurrent.FutureTask;/** * @authorXXX.SJTU * @function * @date May 17, 2017 *@version */ Public classCallablethreadtestImplementsCallable<integer>{@Override PublicInteger Call ()throwsException {inti = 2017; System.out.println (Thread.CurrentThread (). GetName ()+ " " +i); returni; } Public Static voidMain (string[] args) {callablethreadtest CTT=Newcallablethreadtest (); Futuretask<Integer> ft =NewFuturetask<>(CTT); NewThread (FT, "threads with return value")). Start (); Try{System.out.println ("The return value of the child thread:" +ft.get ()); } Catch(interruptedexception e) {e.printstacktrace (); } Catch(executionexception e) {e.printstacktrace (); } }}
3 ways to do Java multi-threading