1. Use thread directly to create
Packagecom.test.tt; Public classThreadexextendsthread{Private intJ; Public voidrun () { for(j=0; j<100;j++) {System.out.println ("The current thread name is:" + getName () + "+" The current value of J is: "+j); } } Public Static voidMain (string[] args) { for(inth=0; h<100;h++){ if(h==20) {Threadex threadTest1=NewThreadex (); Threadex ThreadTest2=NewThreadex (); Threadtest1.start (); Threadtest2.start (); } System.out.println ("The current thread name is:" + thread.currentthread (). GetName () + "+" The value of the current H is: "+h); } }}
2. By implementing the Runnable interface and creating the Runnable implementation object as the thread's target
Packagecom.test.tt; Public classRunnableexImplementsrunnable{Private inti; @Override Public voidrun () { for(i=0; i<100;i++) {System.out.println ("The current thread name is:" + thread.currentthread (). GetName () + "+" The current value of I is: "+i); } } Public Static voidMain (string[] args) { for(intj=0;j<100;j++) {System.out.println ("The current thread name is:" + thread.currentthread (). GetName () + "+" The current value of I is: "+j); if(j==20) {Runnableex REx=NewRunnableex (); Thread Thread1=NewThread (REx, "instance 1"); Thread thread2=NewThread (REx, "Instance 2"); Thread1.start (); Thread2.start (); } } }}
3. Create by implementing the callable interface (this is how a return value is created)
Packagecom.test.tt;Importjava.util.concurrent.Callable;ImportJava.util.concurrent.FutureTask; Public classCallableexImplementscallable{@Override PublicObject Call ()throwsException {intI =0; for(; i<1000;i++) {System.out.println ("The current thread name is:" + thread.currentthread (). GetName () + "+" The current value of I is: "+i); } returni; } Public Static voidMain (string[] args) {//TODO auto-generated Method StubCallableex CEx=NewCallableex (); Futuretask<Integer> task =NewFuturetask<integer>(CEX); for(intj=0;j<1000;j++) {System.out.println ("The current thread name is:" + thread.currentthread (). GetName () + "+" The current value of I is: "+j); if(j==200) {Thread thread1=NewThread (Task, "instance 1"); Thread1.start (); } } Try{System.out.println ("Thread return value:" +task.get ()); }Catch(Exception ex) {ex.printstacktrace (); } }}
How to create multithreading in Java