[Java primary]:21. Multithreading

Source: Internet
Author: User

Overview

Programs: program, is a static concept

Processes: Process, is a dynamic concept

A process is a dynamic execution process of a program that occupies a specific address space.

Each process is independent and consists of 3 parts Cpu,data,code

Cons: Memory waste, CPU burden

Threads: Thread, is a "single continuous control Flow" in the process (a sequential flow ofcontrol)/execution path

Threads are also known as lightweight processes (lightweight process).

Threads run at the same time, independentlyof one another

A process can have multiple parallel (concurrent) threads

A thread in a process shares the same memory unit/memory address space  can access the same variables and objects, and they allocate objects from the same heap  communication, data exchange, synchronous operation

Because the communication between threads is performed on the same address space, no additional communication mechanisms are required, which makes communication easier and the speed of information delivery faster.


Implement

The thread-responsible feature in Java is the Java.lang.Thread class

You can create a new thread by creating an instance of the thread.

Each thread completes its operation by means of the method run () that corresponds to a particular thread object, and the method run () is called the thread body.

Start a thread by calling the start () method of the Thead class.

Disadvantages of inheriting the thread class: that is, if our class has been inherited from a class (such as a small program must inherit from the Applet Class), then the thread class cannot be inherited

Multithreading through the Runnable interface

Pros: You can implement inheritance at the same time. The implementation of the Runnable interface is a bit more generic.

Java provides a thread scheduler to monitor all threads in a program that have entered a ready state after being started. The thread scheduler determines which thread should be dispatched to execute according to the priority of the thread.

The priority of a thread is represented by a number, ranging from 1 to 10

The default priority for a thread is 5

thread.min_priority = 1

Thread.max_priority = 10

Thread.norm_priority = 5

Use the following line method to get or set the priority of the thread object.

Intgetpriority ();

voidsetpriority (int newpriority);

Note: A low priority simply means that the probability of getting a schedule is low. It is not an absolute priority to call a thread with a low priority after it is first called.

Demo

<span style= "FONT-SIZE:18PX;" >public class TestThread2 implementsrunnable {         publicstatic void Main (string[] args) {                   Threadthread1 = new THR EAD (New TestThread2 (1)); Thread thread2 = new Thread (NEWTESTTHREAD2 (2)); t1.setpriority (1);                   T2.setpriority (+); Thread1.start ();                   Thread2.start ();         }         Publicvoid Run () {for                   (inti=0;i<100;i++) {                            System.out.println (this.threadid+ ":" +i);}}         } </span>

Status

New status :
When a thread object is established with the new keyword and the thread class or its subclasses, the thread object is in a new state. A newly-emerging thread has its own memory space, which is entered in a ready state by calling the Start method (runnable)

Ready State :
A thread in the ready state already has a running condition, but has not yet been assigned to the CPU, is in the thread-ready queue, and waits for the system to allocate its CPU. The wait state is not an execution state, and when the system selects a thread object waiting to be executed, it enters the execution state from the waiting execution state, and the system picks the action called "CPU scheduling". Once the CPU is acquired, the thread goes into a running state and automatically calls its own Run method.

Running status :
The thread in the running state executes the code in its own run method until the other method is called to terminate, or wait for a resource to block or complete the task and die. If there is no execution end within a given time slice, it will be replaced by the system and returned to the waiting execution state.

Blocking status :
A running thread in some cases, such as a sleep method, or waiting for a resource such as an I/O device, will give up the CPU and temporarily stop its own operation and go into a blocking state. The thread in the blocking state cannot enter the ready queue. Only when the cause of the blockage is eliminated, such as when the sleep time has elapsed, or the waiting I/O device is idle, the thread goes into a ready state, queues up in the ready queue, and continues to run when the system has been selected and started from where it was originally stopped.

Death status :
The death state is the last phase in the thread's life cycle. There are two causes of thread death. One is the normal running thread that completes all of its work, and the other is that the thread is forced to terminate, such as by executing the stop or Destroy method to terminate a thread [these two methods are not recommended. The former generates an exception, which is forced to terminate and does not release the lock.

Sync and Deadlock

Because multiple threads of the same process share the same piece of storage space, it also poses a serious problem with access violations when it comes to convenience. The Java language provides a specialized mechanism to resolve this conflict, effectively avoiding the same data object being accessed by multiple threads concurrently.

Since we can guarantee that the data object is accessible only by means of the private keyword, we only need to propose a mechanism for the method, which is the Synchronized keyword, which consists of two usages: the Synchronized method and the synchronized block.

The so-called deadlock refers to the situation where multiple processes are waiting indefinitely for the resources they occupy. Obviously, if there is no external force, then the various processes involved in the deadlock will always be in a blocked state. As can be seen from the above example, the root cause of the deadlock is the limited resources and improper operation of the computer system. That is, one reason is that the resources provided by the system are too small to meet the requirements of the concurrent process for resources. The deadlock caused by this competitive resource is the core of our discussion. For example, a message is a temporary resource. At some point, process a waits for a message from process B, process B waits for a message from process C, and process C waits for a message from process a. The message was not reached, a,b,c three processes could not be pushed forward, and deadlock on process communication could occur. Another reason is that the sequence of process advancement is not appropriate for the resulting deadlock. Less resources may not necessarily create deadlocks. Just as two people cross the bridge, if two people have to first, the deadlock in the single-plank bridge will not retreat, it is inevitable that the competition resources to generate deadlock; But if two people go up front and see if there are any other people on the bridges, and when no one else is on the bridge, then the problem is solved. Therefore, if the programming is unreasonable, causing the process to advance the wrong order, there will be deadlock.

Recovery of Deadlocks

Once a deadlock is detected in deadlock detection, the deadlock is eliminated and the system recovers from the deadlock state.

(1) The simplest and most commonly used method is to perform a system reboot, but this method is expensive, which means that all the computations that have been done before that process are lost, including those involved in the deadlock, and the processes that are not involved in deadlocks.

(2) Revoke the process and deprive the resources. Terminates the process that participates in the deadlock, reclaims the resources that they occupy, and thus unlocks the deadlock. At this point there are two situations: one-time undo all the processes involved in the deadlock, deprive all resources, or gradually revoke the process involved in the deadlock, gradually recover the resources occupied by the deadlock process. In general, the process of phasing out is chosen in accordance with certain principles, with the aim of undoing the least costly processes, such as determining the cost of the process by the priority of the process, taking into account factors such as the cost of the process runtime and the cost of the external job associated with the process.

In addition, there is a process fallback policy that lets a process that participates in a deadlock fall back to a point where there is no deadlock, and continue execution at this point, so that a deadlock no longer occurs in order to execute again. Although this is a better approach, but the operation of the system overhead, it is necessary to have the stack such a mechanism to record every step of the process changes, so that the future fallback, sometimes this is not possible.

Task Scheduling

Timer Timer class

TimerTask Task Class

Via Java Timer timetask: (Spring's Task Scheduler is implemented by them)

In this implementation, the timer class implements a function like the alarm clock, which is to trigger a thread at regular intervals or at a certain time. In fact, the timer class itself implements a thread, but this thread is used to implement calls to other threads. The TimerTask class is an abstract class that implements the Runnable interface, so the class has the ability to multithreading, as described earlier.

In this implementation, by inheriting TimerTask, this class gets the ability to multithreading, writing code that requires multi-threaded execution inside the Run method, and then starting the execution of the thread through the Timer class.

In practice, a timer can start a thread of any number of TimerTask implementations, but there is a blockage between multiple threads. So if you need to run completely independently between multiple threads, it's best to start a timertask implementation with a timer.

Business Ideas

Multi-threading mechanism operation, independent instruction flow concurrent execution, makes the user very easy.

All aspects of Java multithreaded programming are described here, including the creation of threads and the scheduling and management of multiple threads. The profound recognition of the complexity of multithreaded programming and the inefficiency of multi-threaded programs caused by thread switching overhead also prompted us to seriously consider a question: do we need multi-threading? When do I need multiple threads?

The core of multithreading is that multiple code blocks are executed concurrently, and the essential feature is that the code between blocks of code is executed in random order. Whether or not our program requires multithreading is to see if this is the intrinsic feature of it.

If our program does not require multiple code blocks concurrent execution, it naturally does not need to use multi-threading, if our program requires multiple code blocks concurrent execution, but does not require chaos, then we can use a loop to be simple and efficient implementation, and do not need to use multithreading; only if it fully conforms to the characteristics of multithreading , the multithreading mechanism's strong support for inter-thread communication and thread management can be useful, and it is worthwhile to use multi-line friend.




[Java primary]:21. Multithreading

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.