Threads in Java (i)

Source: Internet
Author: User
Tags thread class

First, thread and process

When it comes to threading, you have to mention the process, long before there is no thread, only the process, when a program needs to run, must use the system resources and CPU,

As a result, the process is responsible for resource allocation and CPU scheduling for an application. Later, in order to further improve the efficiency of concurrent execution and resource utilization, we proposed

Thread concept, the process is broken down, the process will be responsible for the allocation of resources, threads responsible for CPU scheduling. So can be done with a summary, the process is a process that can be executed concurrently

Sequential execution of a data set, which is the basic unit of system resource allocation, thread is process-owned, as the basic unit of dispatch execution, a process can

has one or more threads that share the resources owned by the owning process.

Ii. processes and Threads in Java

We know that Java programs must run on the JVM, and every time we run a Java program, we start a JVM process, the life cycle of the JVM and the program's life cycle

Consistent, that is, the JVM process exits when the program runs out or when it encounters an exception, and the JVM runs a Java program with a responsibility.

When the JVM runs a Java program, he creates a main thread, which is the main () method that the main thread executes. The task of executing code for the JVM virtual machine is all done by the thread,

Each thread has its own separate program counter and method call stack.


Program counter: When the thread executes the next method, the program counter points to the following bytecode directive to be executed in the method area.

Method Call Stack: Short method stack, used to track the thread run in a series of method call procedures, the stack of elements into the stack frame. Whenever a thread calls a method,

A new frame is pressed into the method stack. Frames are used to store the parameters of the method, local variables, and temporary data during the operation.

The stack frame consists of the following three parts:

Local variable area: Storing local variables and method parameters

Operand stack: is the working area of the thread that holds the temporary data generated during the operation.

Stack data area: Provides relevant information for thread execution instructions, including how to navigate to specific data located in the heap and method areas, and how to exit the method normally or the exception terminal method

Analyze the Java thread's running process in the following code:

public class sample{private int a = 0;  public int method () {int B;  a++;  return A;  } public static void Main (String args[]) {sample S =new sample ();  S.method ();  System.out.println (a); }  }


When the JVM is started to run the above program, the JVM first creates a main thread that has its own program counter and method stack, and begins to enter the main () method, after which he will

The stack frame of the main () method stacks, the local variables, the parameters of the method, and the temporary data of the operation process are deposited into the local variable area and the operand stack in the stack frame respectively, and the same way into method

After the stack frame is pressed into method (), the main thread can correctly locate the instance variable a of the sample object in the heap area according to the information in the stack data area of the method's stack frame, and put its

After the value plus 1,method execution completes, the stack frame of the pop-up method () continues to point to the main () method.

Third, Java thread creation method (4)

Inherit the thread class

Implementing the Runnable Interface

Thread pool

Implementing the Callable Interface

Advantages of the runnable Way (difference):

(1), the task of the thread is separated from the child class of the thread, and a separate encapsulation is carried out. The task is based on the idea of object-oriented

Encapsulate As Object

(2), avoid the limitations of Java single inheritance

So the second way to create threads is more common

Four, the state of the thread (5 kinds)

1. Newly created state (new)

Condition: Created with the new statement

Feature: Memory is allocated only in the heap area

2. Ready state (Runnable)

Condition: When a thread object is created, another thread calls its start () method

Features: Java Virtual Opportunity creates a method call stack and program counter for it, which is located in a running pool and waits for the CPU to be used.

3. Operating status (Running)

Condition: The thread of the runnable state is preempted to the CPU into the running state (only the runnable state can go to the running state)

Features: Exclusive one CPU

4. Blocking status (Blocked)

The blocking state can be divided into the following three situations:

Blocked in object ' Wait pool ' (blocking state in the object's wait pools)

Condition: Wait ()

Blocked in object ' s lock pool (blocking state in object lock pools)

Condition: While waiting to acquire a sync lock

Otherwise Blocked (Other blocking states)

Condition: Sleep () join () I/O request (SYSTEM.OUT.PRINTLN () or System.in.read ())

5. Death status (Dead)

Condition: Exit the Run () method (exit after normal execution or unexpected exit)

Features: No impact on other threads

5. Scheduling of threads

If we do not manage the scheduling of threads, the multi-threaded running sequence is irregular, in fact, even if we manage the thread scheduling, their running timing is not absolutely certain, such as a thread to another thread to run the opportunity to take the following methods:

(1) Adjust thread priority

Java provides 10 priorities, with a range of integers 1~10 (about the mapping between the Java priority and the operating system priority), there are 3 static constants in the Therad class:

L Max_priority: The value is 10, which indicates the highest priority

L Min_priority: value is 1, indicating the lowest priority

L Norm_priority: Value is 5, indicating the default priority

The priority method is set by the setpriority (int) method of the Thread class

All threads in a ready state are placed in a running pool based on priority, with low priority threads getting fewer run opportunities, and higher priority threads getting more running opportunities.

(2) Let the running state thread call the Thread.Sleep () method

If you let a thread call the sleep () method, you can give it an exact value of 1000 milliseconds, but the time from the start of the Sleep (1000) method to the thread's re-entry into the running state is not exactly 1000 milliseconds,

Because it enters the runnable state after 1000 milliseconds, the time from the runnable state to the running state is indeterminate, depending on a number of factors, such as CPU speed, scheduling algorithm, currently running processes or threads, and so on.

(3) Let the running state thread call the Thread.yield () method

And the most proof of the thread management uncertainty is the Thread.yield () method, yield translation is the meaning of "yield", in fact, we can understand it as pretending to yield, because you are a little slower, the next moment to preempt the CPU may be the original thread.

Both the sleep () and yield () methods are static methods of the thread class, leaving the current running thread to abandon the CPU and give the running opportunity to another thread. The difference between the two is:

The 1.sleep () method gives the opportunity for other threads to run, regardless of the priority of the other threads, and the yield () method only gives the same priority or higher priority one run opportunity.

2. When the thread executes the sleep () method, it goes to the blocking state, and when the thread executes the yield () method, it goes to the ready state.

The 3.sleep () method declares that the interruptedexception exception is thrown, and the yield () method does not declare any exceptions to be thrown. So the sleep () statement is placed in the Try-catch.

The 4.sleep () method has better portability than yield (), and in practice it is not possible to rely solely on the yield () method to improve program concurrency.

(4) Let the running state thread call the join () method of another thread

The currently running thread can invoke the join () method of another thread, and the currently running thread will go to the blocking state until another thread finishes running, and it will move from the blocking state to the ready state to get the run opportunity.

Five, The Guardian thread

Concept: A thread that provides services to other threads, also known as a daemon thread. The garbage collection thread of a Java virtual machine is a typical background thread that recycles memory that is no longer used by other threads.

Features: The background thread accompanies the foreground thread, and the background thread may end up before the foreground thread finishes executing, and if the foreground thread is running, the Java Virtual machine terminates the background thread if the join background thread is still running.

This is reflected in the concept of the background thread, the background thread is to serve the foreground thread, if there is no foreground thread in the execution, the background thread is not necessary to exist.

The main thread, by default, is the foreground thread, and the threads created by the foreground thread are foreground threads by default, and threads created by the background thread are still background threads by default.

Set foreground thread to background thread: Call the Setdaemon (True) method of the thread class.

To determine if a thread is a background thread: Call the thread's Isdaemon () method

This article is from the "12212886" blog, please be sure to keep this source http://12222886.blog.51cto.com/12212886/1963919

Threads in Java (i)

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.