Multithreading
one, multi-threaded
1. Process and Thread
process : A running instance of a computer program that contains instructions to be executed, has its own independent address space, contains program content and data, and the address space of different processes is isolated from each other;
processes have various resources and status information, includes open files, sub-processes, and signal processing.
Threads : Represents the execution flow of a program, which is the basic unit of CPU scheduling execution, and threads have their own program counters, registers, stacks, and frames. Threads in the same process share the same address space,
Share memory and other resources owned by the process lock at the same time.
2. Java Standard library provides process and thread-related APIs
The process mainly includes the Java.lang.Process class that represents the process and the Java.lang.ProcessBuilder class that creates the process;
Indicates that the thread is the Java.lang.Thread class , after the virtual machine starts, usually only the Java class Main method This normal thread runs, the runtime can create and start new threads;
There is a class of daemon threads (Damon thread), which runs in the background and provides the services required to run the program. When all the threads running in the virtual machine are daemon threads, the virtual machine terminates running.
3, the life cycle of the thread
A thread is a process that executes dynamically, and it also has a process from generation to death.
-
- new state:
Using new keywords and & nbsp When the thread class or its subclasses establish a thread object, the thread object is in the new state. It remains in this state until the program start () this thread.
- ready state:
When the thread object invokes the start () method, the thread enters the ready state. The ready state thread is in the ready queue, waiting for the thread scheduler in the JVM to dispatch.
- Run State:
If the thread in the ready state acquires CPU resources, it can execute run () , at which point the thread is running. A running thread is the most complex and can become a blocking state, a ready state, and a dead state.
- blocked state:
If a thread executes a method such as sleep, suspend (hang), and so on, the thread will enter a blocking state from the running state after it loses its resource. You can re-enter the ready state after the sleep time has arrived or the device resource has been acquired. Can be divided into three types:
-
Waits for blocking: The thread in the running state executes the wait () method, causing the thread to go into a wait-blocking state.
-
Synchronous blocking: The thread has failed to acquire the synchronized synchronization lock (because the synchronization lock is occupied by another thread).
-
Other blocking: When an I/O request is made by the calling thread's sleep () or join (), the thread enters the blocking state. When the sleep () state times out, the join () waits for the thread to terminate or time out, or the I/O process completes and the thread is re-entered in a ready state.
- dead state:
When a running thread finishes a task or another termination condition occurs, the thread switches to the terminating state.
4. Priority of Threads
Each Java thread has a priority, which helps the operating system determine the order in which the threads are dispatched.
The priority of a Java thread is an integer whose value range is 1 (thread.min_priority)-Ten (thread.max_priority).
By default, each thread will be assigned a priority of norm_priority (5).
A thread with a higher priority is more important to the program, and the processor resources should be allocated before a low-priority thread. However, thread precedence does not guarantee the order in which threads are executed, and is very dependent on the platform.
5. Creation of threads
Java provides three ways to create threads:
-
- By implementing the Runnable interface;
- By inheriting the Thread class itself;
- Create threads from callable and future.
1 . Create a thread by implementing the Runnable interface
(1) Define the implementation class for the Runnable interface, and override the run () method of the interface, which is also the thread execution body of the thread of the Run () method.
(2) Create an instance of the Runnable implementation class, and use this instance as the target of the thread to create the thread object, which is the true thread object.
(3) Call the Start () method of the thread object to start the thread.
Example:
1 PackageCom.thread; 2 3 Public classRunnablethreadtestImplementsRunnable4 { 5 6 Private inti; 7 Public voidRun ()8 { 9 for(i = 0;i <100;i++) Ten { OneSystem.out.println (Thread.CurrentThread (). GetName () + "" +i); A } - } - Public Static voidMain (string[] args) the { - for(inti = 0;i < 100;i++) - { -System.out.println (Thread.CurrentThread (). GetName () + "" +i); + if(i==20) - { +Runnablethreadtest RTT =Newrunnablethreadtest (); A NewThread (RTT, "New Thread 1"). Start (); at NewThread (RTT, "New Thread 2"). Start (); - } - } - - } - in}
2. Inherit the thread class to create a threading class
(1) Define a subclass of the thread class and override the Run method of the class, which represents the task that the thread will complete. So the run () method is called the actuator.
(2) Create an instance of the thread subclass, that is, the threading object is created.
(3) Call the Start () method of the thread object to start the thread.
1 PackageCom.thread; 2 3 Public classFirstthreadtestextendsthread{4 inti = 0; 5 //rewrite the Run method, the method body of the Run method is the field execution body6 Public voidRun ()7 { 8 for(; i<100;i++){ 9System.out.println (GetName () + "" +i); Ten One } A } - Public Static voidMain (string[] args) - { the for(inti = 0;i< 100;i++) - { -System.out.println (Thread.CurrentThread (). GetName () + ":" +i); - if(i==20) + { - Newfirstthreadtest (). Start (); + Newfirstthreadtest (). Start (); A } at } - } - -}
The Thread.CurrentThread () method in the preceding code returns the currently executing thread object. The GetName () method returns the name of the thread that called the method.
3. Create threads through callable and future
(1) Create an implementation class for the callable interface and implement the call () method, which will act as the thread execution body and have a return value.
(2) Create an instance of the callable implementation class, using the Futuretask class to wrap the callable object, which encapsulates the return value of the call () method of the Callable object.
(3) Use the Futuretask object as the target of the thread object to create and start a new thread.
(4) Call the Get () method of the Futuretask object to get the return value after the child thread execution ends
Example:
1 PackageCom.thread; 2 3 Importjava.util.concurrent.Callable; 4 Importjava.util.concurrent.ExecutionException; 5 ImportJava.util.concurrent.FutureTask; 6 7 Public classCallablethreadtestImplementsCallable<integer>8 { 9 Ten Public Static voidMain (string[] args) One { ACallablethreadtest CTT =Newcallablethreadtest (); -futuretask<integer> ft =NewFuturetask<>(CTT); - for(inti = 0;i < 100;i++) the { -System.out.println (Thread.CurrentThread (). GetName () + "The value of the loop variable i" +i); - if(i==20) - { + NewThread (FT, "threads with return value")). Start (); - } + } A Try at { -System.out.println ("The return value of the child thread:" +ft.get ()); -}Catch(interruptedexception e) - { - E.printstacktrace (); -}Catch(executionexception e) in { - E.printstacktrace (); to } + - } the * @Override $ PublicInteger Call ()throwsExceptionPanax Notoginseng { - inti = 0; the for(; i<100;i++) + { ASystem.out.println (Thread.CurrentThread (). GetName () + "" +i); the } + returni; - } $ $}
4. Comparison of three ways to create threads
With the implementation of the runnable, callable interface, transcend multi-threading,
The advantages are:
The thread class simply implements the Runnable interface or callable interface and can inherit other classes.
In this way, multiple threads can share the same target object, so it is very suitable for multiple identical threads to handle the same resource, so that the CPU, code and data can be separated to form a clear model, which is a good embodiment of object-oriented thinking.
Disadvantages are:
Programming is slightly more complex, and you must use the Thread.CurrentThread () method if you want to access the current thread.
When you create a multi-threaded method with the Inherit thread class
The advantages are:
Writing is simple and if you need access to the current thread, you do not need to use the Thread.CurrentThread () method to get the current thread directly using this.
Disadvantages are:
The thread class has inherited the thread class, so it is no longer possible to inherit other parent classes.
5, Summary:
on the use of multithreading: the key to effective use of multithreading is to understand that programs are executed concurrently rather than serially. For example, there are two subsystems in the program that need to be executed concurrently, which requires multithreaded programming.
In addition, when multithreaded programming:
Focus on understanding:
-
-
-
- Thread synchronization
- Inter-thread communication
- Thread deadlock
- Line programmed: Suspend, stop, and resume
Reference Blog: http://blog.csdn.net/escaflone/article/details/10418651
http://blog.csdn.net/longshengguoji/article/details/41126119
Http://www.runoob.com/java/java-multithreading.html
http://www.tiantianbianma.com/java-wait-notify.html/
Java Advanced Learning--java multithreading