Keywords: Thread, Runnable, synchronized
The current CPU is very powerful, generally multiple cores, and uses hyper-threading technology, so that one core can run multiple threads in parallel. When processing big data, multithreading will greatly speed up data processing, and multi-threaded programming is also becoming increasingly important. In Java, each program is running with a main thread.
Two ways to create a Thread: Inherit the Thread and implement Runnable
Class A extends Thread
Thread implements Runnable
Directly calling the run () method is not a multi-thread, but a method for running objects. To create multiple threads, you need to call the operating system resource-CPU. In the Thread's start () method, native's start () is called to create a new Thread (native Description: http://blog.csdn.net/fsz521/article/details/8748562 ).
For example, multiple threads control sequential execution: three threads output their IDs in sequence.
Output: 012012012
package multiThread;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;class TestThreadMethod extends Thread {public TestThreadMethod(String name) {super(name);}public void run() {System.out.print(this.getName());}}public class TestThread {public static void main(String[] args) {TestThreadMethod ttm0 = new TestThreadMethod("0");TestThreadMethod ttm1 = new TestThreadMethod("1");TestThreadMethod ttm2 = new TestThreadMethod("2");ExecutorService exec = Executors.newSingleThreadExecutor();for (int i = 0; i < 3; i++) {exec.execute(ttm0); exec.execute(ttm1);exec.execute(ttm2);}exec.shutdown();}}