Black Horse Programmer------The summary of multithreading in Java (i)

Source: Internet
Author: User

Java training, Android training, iOS training,. NET training </a>, look forward to communicating with you!

First, the concept of multithreading

Process: is a "self-containment" of the running program, has its own address space. A process-based feature that allows a computer to run two or more programs at the same time

Thread: is a single sequential control flow within a process. In a thread-based multitasking environment, a thread is the smallest processing unit.

In Java, an application can contain multiple threads. Each thread performs a specific task and can execute concurrently with other threads. Multithreading reduces the idling time of the system and improves the CPU utilization. Multithreaded programming hides the fact that the CPU switches between tasks.

Second, create the thread

Create a thread object with two methods:
1. Declare a subclass of the thread class and overwrite the run () method.

Class Mythread extends thread{public    void Run () {/* Overwrite the method */}}

2. Declare a class that implements the Runnable interface and implement the run () method

Class Mythread implements runnable{public    void Run () {/* Overwrite the method */}}

To trigger a new thread, use the Start () method, such as:

Mythread t = new Mythread (); T.start ();

When the start () method is called, a new control thread is created, and then it calls the run () method. The code in the Run () method defines the functionality required to execute the thread.
Create Thread Example:

Class MyThread extends thread{public    void Run ()    {        System.out.println ("Child thread is:" +thread.currentthread ());    } Public    static void Main (string[] agrs)    {        Thread t = thread.currentthread ();        System.out.println ("Main thread is:" +t);        MyThread ex = new MyThread ();        Ex.start ();    }}

Third, the state of the thread

1. New (Bron): New thread is in new state.
2. Ready: After the thread is created, it will be in the ready state, waiting for the start () method to be called
3. Run (Running): The thread enters the running state at the start of execution
4, Sleep (sleeping): Thread execution can be temporarily aborted by the sleep () method. After sleep, the thread enters the ready state.
5. Wait (waitiing): If the Wait () method is called, the thread will be in a wait state. Used when two or more threads are running concurrently.
6. Suspend (Suspended): The thread is in a suspended state when the execution of a temporary stop or interrupt thread is executed.
7. Resume: When a suspended thread is resumed execution, it can be said that it has been restored.
8, blocking (Blocked): When the thread waits for an event (such as an input/output operation), it is in a blocked state.
9. Death (Dead): The thread is in a dead state after the run () method has completed execution or its stop () method is called.

The state of the thread:

Conditions that can cause a thread to pause execution:

-Thread priority is low, so CPU time is not available.
-Use the Sleep () method to make the thread sleep.
-Causes the thread to wait by calling the Wait () method.
-by invoking the yield () method, the thread has explicitly assigned CPU control.
-the thread is blocked because it waits for a file I/O event.

A simple example of thread state:

Class Threadstatedemo extends thread{    Thread t;    Public Threadstatedemo ()    {        t = new Thread (this);        SYSTEM.OUT.PRINTLN ("Thread t is new! ");        SYSTEM.OUT.PRINTLN ("Thread t is ready! ");        T.start ();    }    public void Run ()    {        try        {            System.out.println ("Thread T is running! ");            T.sleep (+);            SYSTEM.OUT.PRINTLN ("Thread T" re-runs after a short time of sleep!) ");        }        catch (interruptedexception e)        {            System.out.println (e.tostring ());        }    }    public static void Main (string[] args)    {        new Threadstatedemo (). Start ();    }}

Operation Result:

Four: Important methods in the thread class:

1, static int enumerate (thread[] t): Copies all active threads in the thread group in which the thread resides and its subgroups, and returns the number of threads in the specified array.
2. Final String getName (): Returns the name of the thread.
3. Final Boolean isAlive (): Returns True if the thread is active, otherwise false.
4. Final void SetName (String name): Sets the name of the thread to the specified name.
5. Final void Join () throws Interruptedexception: Waiting for thread to end
6. Final Boolean Isdaemon (): Checks whether the thread is a daemon thread (Guardian thread)
7. Final void Setdaemon (Boolean on): Marks a thread as a sprite thread or user thread based on the parameters passed in
8. static void Sleep (): Used to suspend a thread for a period of time.
9, void Start (); Call the Run () method to start the thread and start the execution of the thread.
10, static int Activecount (): Returns the number of active threads
11. static void Yield (): Causes the executing thread to temporarily pause and allow other threads to execute.

Five, Thread priority

Thread Precedence in Java is a constant defined in the thread class

-norm_priority: A value of 5
-max_priority: A value of 10
-min_priority: A value of 1

Default priority is Norm_priority

There are two ways to prioritize:
-final void setriority (int newp): Modifies the current priority of the thread.
-final int getpriority (): Returns the priority of the thread.

Summarize:
Thread blocking may be due to the following five reasons: ("Thinking in Java")

1. Call sleep (in milliseconds) to put the thread into sleep. This thread will not run for a specified period of time.

2. Suspend execution of the thread with suspend (). The "operational" status is not returned unless a resume () message is received.

3. Suspend execution of the thread with Wait (). Unless the thread receives a notify () or notifyall () message, it does not become a "operational" state.

4. The thread is waiting for some IO operations to complete.

5. The thread tries to invoke the "synchronous" method of another object, but that object is locked and temporarily unusable.

Black Horse Programmer------The summary of multithreading in Java (i)

Related Article

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.