One, threads, and processes
1. What are the differences between threads and processes:
A thread is an execution unit in which a program can execute program code during execution. In the Java language, threads have four states: Run, ready, suspend, and end.
A process is a procedure that is being executed. And thread things are also a lightweight process, he has the smallest unit of program execution, a process that can have multiple threads, sharing the internal strength of a program (code snippets, data segments, and heap space) and some process-level resources (such as open files), but each thread has its own hoteis space.
2. Why to use multiple processes
At the operating system level, there are several main aspects:
-Use multithreading to reduce the response time of the program, if an operation and time-consuming, or into a long wait, this time the program will not respond to the mouse and keyboard operations, such as the use of multiple threads can be used to allocate this time-consuming thread to a separate thread to execute, so that the program has a better interaction.
-Thread creation and switching overhead are smaller than processes, and multithreading is highly efficient at data sharing.
-Multi-CPU or multi-core computers themselves have the ability to perform multithreading, if the use of a single process, will not be able to reuse computer resources, resulting in a huge waste of resources. Using multithreading on a multiple-CPU computer can improve CPU utilization.
-Multithreading simplifies the structure of programs, making programs easier to understand and maintain
second, create a thread
The implementation of multithreading generally has the following three methods, the first two of which are the most common methods:
1. Inherit the thread class and rewrite the Run () method
thread is essentially an instance of implementing the Runnable interface. Note that the call to the start () method does not immediately execute multithreaded code, but rather makes the thread operational, and when running multithreaded code is determined by the operating system.
The following are the main steps:
(1) Define subclasses of the thread class and override the Run method of the class, which represents the task the thread is to complete. So the run () method is called the execution body.
(2) Create an instance of the thread subclass, that is, the thread object is created.
(3) invokes the start () method of the thread object to start the thread.
public class Testthread extends thread{public
void Run () {
System.out.println ("Hello World");
}
public static void Main (string[] args) {
Thread mthread = new Testthread ();
Mthread.start ();
}
2. Implement the Runnable interface and implement the run () method of the interface
The following are the main steps:
(1) Customizing the class and implementing the Runnable interface to implement the run () method.
(2) Creates an instance of the thread subclass and instantiates the thread object as a parameter with the object implementing the Runnable interface.
(3) Call the thread's start () method to start it.
public class Testrunnable implements Runnable {public
void run () {
System.out.println ("Hello World");
}
Public
class Testrunnable {public
static void Main (string[] args) {
testrunnable mtestrunnable = new Testru Nnable ();
Thread mthread = new Thread (mtestrunnable);
Mthread.start ();
}
3. Implement callable interface, rewrite call () method
The callable interface is actually a functional class within the executor framework, and the callable interface is similar to the Runnable interface, but provides a more powerful feature than the runnable, which is represented by the following 3 points:
(1) callable can provide a return value after the task is accepted, runnable cannot provide this functionality.
(2) The call () method in callable can throw an exception, and the Runnable run () method cannot throw an exception.
(3) The running callable can get a future object, future object represents the results of the Ituri calculation, he provides a way to check whether the calculation is complete. Because the thread belongs to the asynchronous computing model, as a result, the return value of the function cannot be obtained from another thread, in which case the future can be used to monitor the call () method by the target thread, but when the future get () method is invoked to obtain the result, the current thread blocks, knowing that call ( Returns the result of the method.
public class Testcallable {
//Create thread class public
static class Mytestcallable implements callable {public
String CA LL () throws Exception {
Retun "Hello World";
}
}
public static void Main (string[] args) {
mytestcallable mmytestcallable= new mytestcallable ();
Executorservice Mexecutorservice = Executors.newsinglethreadpool ();
Future mfuture = Mexecutorservice.submit (mmytestcallable);
The try {
//waits for the thread to end and returns the result
System.out.println (Mfuture.get ());
} catch (Exception e) {
E.printstacktrace ();
}
The output of the above program is: Hello World
In these three ways, it is generally recommended to implement the Runnable interface, because: First, the thread class defines a variety of methods that can be overridden by derived classes, but only the run () method must be overridden to implement the main function of this thread, This is also the way to implement the Runnable interface. Second, a class should be inherited when they need to be strengthened or modified. Therefore, if it is not necessary to rewrite other methods of the thread class, it is best to implement the Runnable interface in this case.
three, in the disconnection process
The thread terminates when the thread's run () method executes the last statement in the method body and returns by executing the return statement, or when an exception that is not caught in the method is present. In earlier versions of Java, there was a stop method that other threads could call to terminate the thread, but the method is now deprecated.
The interrupt method can be used to request a terminating thread, and when a thread calls the interrupt method, the interrupt state of the thread is placed. This is a Boolean flag that no thread has, and each thread should periodically check the flag to determine if the thread is interrupted.
To find out if a thread is being set, you can call Thread.CurrentThread (). isinterrupted ():
while (! Thread.CurrentThread (). isinterrupted ()) {do
something
}
However, if a thread is blocked, the interrupt state cannot be detected. This is where the interruptedexception is produced. Call the interrupt method on a blocked thread (call sleep or wait). Blocking calls will be interrupted by Interruptedexception.
If the Sleep method (or other interruptible method) is invoked after each iteration, the isinterrupted detection is not necessary or useful, and if you call the Wake method when the interrupt state is placed, It does not hibernate but clears this state and throws a interruptedexception. So if you call sleep in a loop, do not detect the interrupt state, just capture the interruptedexception.
In many published code it is found that interruptedexception is suppressed at a very low level:
void MyTask () {
...
try{Sleep
(}catch)
(interruptedexception e) {
...
}
}
Instead of doing this, there are two reasonable options if you don't think there's any benefit in a catch in a deal:
Call Thread.CurrentThread (). Interrup () in the catch to set the interrupt state. The caller can detect it
Better choose to mark your method with throw interruptedexception, without using a try statement block to capture the form. The caller can then catch this exception:
void MyTask () throw interruptedexception{sleep
()
}
Iv. State of the thread
(1). New State (new): A newly created thread object.
(2). Ready state (Runnable): After the thread object is created, other threads call the object's start () method. The thread of this state is in the running thread pool, becomes operational, and waits for access to the CPU.
(3). Running state (Running): A ready-state thread acquires the CPU and executes the program code.
(4). Blocking state (Blocked): Blocking state is the thread for some reason to give up the use of CPU, temporarily stop running. Until the thread enters the ready state, there is an opportunity to go to the running state. The blocking situation is divided into three types:
-Wait for blocking: The running thread executes the wait () method, and the JVM puts the thread into the waiting pool.
-Synchronous blocking: When a running thread acquires a synchronized lock on an object, the JVM puts the thread into the lock pool if the synchronization lock is occupied by another thread.
-Other blocking: The running thread executes the sleep () or join () method, or when an I/O request is made, the JVM puts the thread into a blocking state. When the sleep () state times out, join () waits for the thread to terminate or timeout, or the I/O process completes, the thread is back in ready state.
(5). Death status (Dead): The thread finishes or exits the run () method because of an exception, which ends the lifecycle.
V. Priority of threads and daemon threads
1. Thread Priority
in Java, each thread has a priority, by default, a thread inherits the priority of its parent class. You can use the SetPriority method to increase or decrease any one thread priority. You can set the priority to any value between min_priority (defined as 1 in the thread Class) and max_priority (defined as 10 in the thread Class). The thread's default priority is norm_priority (defined in the thread class as 5).
Try not to rely on priority, if you really want to use, should avoid a beginner often make a mistake. If there are several high-priority threads that are not inactive, the low-priority thread may never be able to execute. Whenever the scheduler decides to run a new thread, it first makes a selection in a thread that has priority, although it causes the low-priority thread to starve to death altogether.
2. Daemon Threads
Call Setdaemon (True), and convert the thread to a daemon thread. The only purpose of a daemon is to provide services to other threads. The timing thread is an example of a time when he sends a signal to another thread or empties an outdated thread that tells the cached item. When only the daemon thread is left, the virtual machine exits, because if only the daemon is left, there is no need to continue running the program.
In addition, the JVM's garbage collection, memory management, and other threads are daemon threads. There is in doing database application, the use of the database connection pool, the connection pool itself also contains a lot of background threads, monitoring the number of connections, timeout time, state and so on.
The above is about Java multithreading thread definition, status and attributes, I hope to help you learn.