Threads are a sequence of task control flows in a process, and multithreading is the foundation of concurrent programming because process creation and destruction require destroying large amounts of resources and multiple threads can share process data.
Multi-core CPU can realize the implementation of multiple tasks in parallel, single core CPU program is not really parallel operation, but through the time slice switch to execute, because the time slice switch frequently, the user feels the program is running in parallel. In a single core CPU, when performing multithreaded tasks through time slices, although the thread context needs to be saved, it can greatly improve the efficiency of the program because it is not blocked by blocked threads.
1. Status and switching of threads:
The 7 states of the thread and their toggle diagram are as follows:
2. Multithreading Simple Threading Example:
There are two common ways to implement multithreading in Java: Implement Runnable interface and inherit thread class.
(1). The multithreading example for inheriting the thread class is as follows: [Java] View plain copy class primethread extends thread { long minPrime; primethread (long minprime) { this.minPrime = minPrime; } //rewrite the thread class Run method public void run () { . . . } }
How to start inheriting thread class threads: [Java] view plain copy primethread p = new Primethread (143); P.start ();
(2). The multithreading example for implementing the Runnable interface is as follows: [Java] view plain Copy class Primerun implements Runnable {long minprime; Primerun (Long minprime) {this.minprime = Minprime; public void Run () {...} }
Start the method that implements the Runnable interface thread: [Java] view plain copy primethread p = new Thread (new Primethread (143)); P.start (); Because of the single inheritance feature of Java and the principle of object-oriented programming, it is recommended to implement Java multithreading by implementing Runnable interface.
3. Use the executors thread pool:
In JDK5, the introduction of the executors thread pool in the Java.util.concurrent package makes it more convenient and efficient to create multithreading, as shown in the following example:[Java] View plain copy import java.util.concurrent.*; public class cachedthreadpool{ public static void main (String[] args ) { //Create a buffer thread pool service executorservice exec = executors.newcachedthreadpool (); for (int i=0; i<5; i++) { //thread pool service startup threads exec.execute ( new runnable () { //Java Threads public void implemented using anonymous inner classes run () { system.out.println ("Thread ") + i + "&nbsP;is running ");