1. Inherit the thread class, overriding the Run method (in fact the thread class itself implements the Runnable interface)
2. Implement the Runnable interface, overriding the Run method
3. Implement the callable interface, overriding the call method (with a return value)
4. Using the thread pool (with return values)
1. Inherit the thread class, overriding the Run method
Each time a new thread is created, create an object of the thread subclass
Start thread, new thread subclass (). Start ()
public class MyThread {public static void main (String ards[]) {for (int i=0;i<10;i++) { new Extendsthread (). Start (); } System.out.println (Thread.CurrentThread (). GetName ()); } } Class Extendsthread extends thread{ @Override public void Run () {System.out.println ( Thread.CurrentThread (). GetName ()); }}
2. Implement the Runnable interface, overriding the Run method
No matter how many threads are created, you only need to create an object of the Runnable interface implementation class
The start thread, new thread (the object of the Runnable interface implementation Class). Start ()
public class MyThread {public static void main (String ards[]) { Runnable implrunnable = new Implrunna BLE (); for (int i=0;i<10;i++) { new Thread (implrunnable). Start (); } System.out.println (Thread.CurrentThread (). GetName ()); } } Class Implrunnable implements runnable{private volatile int i = 0; @Override public void run () {System.ou T.println (Thread.CurrentThread (). GetName () + "--" + i++); }
3. Implement the callable interface, overriding the call method (with a return value)
When a custom class implements the callable interface, you must specify the generic, which is the type of the return value
Each time you create a new thread, you create a new implementation class for the callable interface,
How do I start a thread?
(1) An object that creates an implementation class for an callable interface
(2) Create a Futuretask object, passing in the parameters of the callable type
Public Futuretask (callable<v> callable) {...}
(3) Call the thread class overload to create a thread object for the Runnable constructor
Passing the Futuretask as a parameter
public class Futuretask<v> implements Runnablefuture<v>
Public interface runnablefuture<v> extends Runnable, future<v>
How do I get the return value?
Call the Get () method of the Futuretask class
public class MyThread {public static void Main (String ards[]) throws Interruptedexception, executionexception{for (int i=0;i<10;i++) { callable<integer> implcallable = new Implcallable (); futuretask<integer> futuretask = new futuretask<integer>(implcallable); New Thread (Futuretask). Start (); System.out.println (Thread.CurrentThread (). GetName () + "----" +futuretask.get ());} System.out.println (Thread.CurrentThread (). GetName ()); }}class Implcallable implements callable<integer>{@Override public Integer call () throws Exception {int result = 0; for (int i=0;i<10;i++) {result + = i;} System.out.println (Thread.CurrentThread (). GetName ()); return result;}}
4. Thread pool
Executors class
PackageMulti.thread;Importjava.util.concurrent.Callable;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.Future;/** * @authorduanjiaping * @date 2018/6/11 22:02 * * thread pool * Similar to database connection pool * avoids additional overhead caused by thread creation and destruction * * java.util.concurrent * * Executor Root interface for ready-to-use and dispatch * |--executorservice thread pool main interface * |--threadpoolexecutor thread pool Implementation class * |--scheduledexe Cutorservice interface, responsible for thread scheduling * |--scheduledthreadpoolexecutor (extends Threadpoolexecutor implements Schedul Edexecutorservice) * * * * Executors Tool class * Provides a way to create a thread pool * **/ Public classThreadPool { Public Static voidMain (string[] args) {//to create a thread pool using a method in the Executors tool classExecutorservice pool = Executors.newfixedthreadpool (5); ThreadPoolDemo Demo=NewThreadPoolDemo (); //Assign a task to a thread in a thread pool, using the Submit method, the passed in parameter can be an implementation class of runnable, or it can be an implementation class of callable for(inti=1;i<=5;i++) {Pool.submit (demo); } //Close the thread pool//shutdown: Shuts down the thread pool in a peaceful way, waits for all tasks in the thread pool to end before shutting down thread pools, not accepting new tasks//Shutdownnow: Immediately close the thread poolPool.shutdown (); }}classThreadPoolDemoImplementsrunnable{/**multi-threaded shared data*/ Private inti = 0; @Override Public voidrun () { while(i<=50) {System.out.println (Thread.CurrentThread (). GetName ()+ "---" + i++); } }}
Importjava.util.concurrent.Callable;Importjava.util.concurrent.ExecutionException;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.Future; Public classThreadPool2 { Public Static voidMain (String args[]) {executorservice Executorservice= Executors.newfixedthreadpool (5); for(inti=0;i<5;i++) { future<Integer> future = Executorservice.submit (NewCallable<integer>() {@Override PublicInteger Call ()throwsException {intresult = 0; for(inti=0;i<=10;i++) {result+=i; } returnresult; } }); Try{System.out.println (Thread.CurrentThread (). GetName ()+"--"+future.get ()); } Catch(Interruptedexception |executionexception e) {E.printstacktrace (); }} executorservice.shutdown (); }}
Java Multithreading Implementation (four methods)