Java multi-threading implementation ways mainly contain three:
- Inherit the “Thread class”
- Realized the “Runnable interface”
- ExecutorService, Callable, Future
- The former two ways have no return value after the thread execution, only the last one is with a return value.
Thread
1 | public class MyThread extends Thread{ |
1 | MyThread myThread = new MyThread(); |
Runnable
1 | public class MyThread extends OtherClass implements Runnable{ |
1 | MyThread myThread = new MyThread(); |
ExecutorService, Callable, Future
1 | int taskSize = 4; |
- Statements
// public static ExecutorService newFixedThreadPool(int nThreads)
// create fixed number of threads
// public static ExecutorService newCachedThreadPool()
// * create scheduled pool, which can instead of the Timer class
// public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)