Java multi-threading implementations can be implemented in the following four ways
1. Inherit the thread class, overriding the Run method
2. Implement the Runnable interface, overriding the Run method
3. Creating threads through callable and Futuretask
4. Creating threads from the thread pool
Not to repeat the way.
Mode 3, multithreading is achieved by creating threads with callable and Futuretask
@Test public void Mycallabletest () throws Exception { //Create thread Execution Object mycallable mycallable = new Mycallable (); futuretask<string> futuretask = new futuretask<>(mycallable); Threading Thread = new Thread (futuretask); Thread.Start (); Gets the thread method return data System.out.println (Futuretask.get ());}/** * Create implementation class */class Mycallable implements callable<string& Gt {@Override public String ' call ' () throws Exception {System.out.println ("Test thread by callable"); return " Result ";}}
Mode 4, creating threads from the thread pool
public classThreadpoolstu {@Test public void TestThreadPool1 () throwsInterruptedexception, executionexception {executorservice executorservice = Executors.newfixedthreadpool (2); Implementing the Runnable Interface implementation class Mode 1 myrunnable runnable1 = newmyrunnable (); Executorservice.execute (RUNNABLE1); Implement the Runnable interface implementation class Mode 2 myrunnable runnable2 = new myrunnable (); future<?> Future2 = executorservice.submit (runnable2); System.out.println (Future2.get ());//If it is not done, it will block the thread//Execute callable Interface Implementation class Mycallable Callable3 = new mycallable (); future<string> future3 = executorservice.submit (callable3); System.out.println (Future3.get ());//If you do not finish, you will block the thread//shut down the Threads Pool executorservice.shutdown ();}} Class Mycallable implements callable<string>{@Override public String call () throws Exception {System.out. println ("Test thread by callable"); return "result";}} Class Myrunnable implements Runnable {@Override public void run () {System.out.println ("thread Execute"); }}
Four ways to implement Java threads