Multithreaded Java Chapter (i)

Source: Internet
Author: User

Before parsing the Asynctask source code, first describe the Java threading knowledge associated with it:

List of knowledge points
1. Thread class
2. Runnable interface
3. Callable Interface
4. Synchronized key Words
5. Volatile keyword
6. Future interface
7. Runnablefuture interface
8, Futuretask class
9, thread pool related knowledge

/**     * A representation of a thread ' s state. A given thread may is in the one     * state at a time.     */Public    enum State {        /**         * The thread had been created, but had never been started.        */NEW,        /** * The thread may be         run.         */        RUNNABLE,        /** * The thread is blocked and waiting for         a lock.         */        BLOCKED,        /** * The thread is         waiting.         */        waiting,        /** * The thread is waiting for         a specified amount of time.        */timed_waiting,        /** * The thread has         been terminated.         */        TERMINATED    }

It is found in this enumeration that there are six states in the list, in fact there are only four states of threads:
1. NEW: When a thread is created, it is only briefly in this state. At this point it has allocated the required system resources and performed the initialization. Now that the thread is eligible for cpy time, the scheduler will turn the thread into a running or blocking state.
2. Ready (RUNNABLE): In this state, the thread can run as long as the scheduler allocates the time slice to the thread. That is, the thread can run or not run at any point in time. As long as the scheduler can allocate time slices to the thread, it can run; This is different from the death and blocking states.
3, blocking (BLOCKED, waiting, timed_waiting): The thread can run, but there is a condition that prevents it from running. When a thread is in a blocked state, the scheduler ignores the thread and does not allocate any CPU time to the thread. It is possible to perform operations until the thread is back in a ready state
4. Death (TERMINATED) the thread that is in the dead or terminated state will no longer be scheduled, and will no longer receive CPU time, its task has ended, or is no longer operational. The usual way to kill a task is to return from the Run method, but the thread of the task can also be interrupted, as you will see.
Here are some examples of how to demonstrate these six states:

public class ThreadTest {public static void main (string[] args) {final thread thread = new Thread (New Runnable                () {@Override public void run () {for (int i = 0; i < 10000; i++) {        }            }        });        SYSTEM.OUT.PRINTLN ("Thread name" + thread.getname () + "thread State" +thread.getstate ());        Thread.Start ();        SYSTEM.OUT.PRINTLN ("Thread name" + thread.getname () + "thread State" +thread.getstate ()); Thread threadtest = new Thread (new Runnable () {@Override public void run () {System.            OUT.PRINTLN ("Thread name" + thread.getname () + "thread State" +thread.getstate ());        }        });        SYSTEM.OUT.PRINTLN ("Thread name" + threadtest.getname () + "thread State" +threadtest.getstate ());        Threadtest.start ();        SYSTEM.OUT.PRINTLN ("Thread name" + thread.getname () + "thread State" +thread.getstate ());    SYSTEM.OUT.PRINTLN ("Thread name" + threadtest.getname () + "thread State" +threadtest.getstate ()); }}

Print Log 1:

Thread name Thread-0 thread State new
Thread name Thread-0 thread state runnable
Thread name Thread-1 thread State new
Thread name Thread-0 thread state terminated
Thread name Thread-1 thread state runnable
Thread name Thread-0 thread state terminated

Print Log 2:

Thread name Thread-0 thread State new
Thread name Thread-0 thread state runnable
Thread name Thread-1 thread State new
Thread name Thread-0 thread state runnable
Thread name Thread-1 thread state runnable
Thread name Thread-0 thread state runnable

public class Threadtesttwo {public    static void Main (string[] args) {        thread thread = new Thread (new Runnable () { c2/> @Override public            void Run () {for                (int i = 0; i < 1000000000; i++) {                }}}        );        SYSTEM.OUT.PRINTLN ("Thread name" + thread.getname () + "thread State"                + thread.getstate ());        Thread.Start ();        SYSTEM.OUT.PRINTLN ("Thread name" + thread.getname () + "thread State"                + thread.getstate ());        try {            thread.sleep (1);        } catch (Interruptedexception e) {            //TODO auto-generated catch block            E.printstacktrace ();        }        SYSTEM.OUT.PRINTLN ("Thread name" + thread.getname () + "thread State"                + thread.getstate ());}    }

 

Print log:

 thread name  Thread- 0 thread state new thread name thread- 0 thread state runnable thread name thread- 0 thread state runnable  

Let me analyze these logs for you:
As you can see, the first thread is thread, the thread's state is new (new state) before the Thread.Start () method call, and the thread's status is Runnbale (ready state) after the Thread.Start () method call. After the task has finished executing the state becomes Terimal (terminating state), you may find that print log 1 and print log 2 are slightly different, because when the thread threadtest is started, the task of thread does not have to be completed is actually an unknown and uncertain thing. This test code also has a knowledge point, we have not found that the final log printing results show that the last log printing is Thread-0, many people have to ask the last log should not be ThreadTest (Thread-1), In fact, it's not because the threadtest is executed in the main thread, and there is a print in the ThreadTest method, so the print log in the Threadtest.run () method is the last one, and the main thread priority is higher than the normal thread. But don't use precedence to control the order in which threads are executed, because that's not reliable. But because the priority of this part of the use of very little, is not very important, here is not discussed in detail, interested can go to see.
Through this part of the test code we know the thread of this class of three states, summed up:
1. The state of a thread is new after a thread is created without calling the Thread.Start () method
2, after a thread calls the Thread.Start () method, the state of the thread is runnable, regardless of whether the thread is in the running state, you can see the second log called the Thread.Sleep () method thread state and no change can be learned
3. After a thread finishes performing a task, the state of the thread is Terimal (end)

The following for everyone on the thread of another State blocking, blocking state is divided into three kinds (BLOCKED, waiting, timed_waiting), in the blocking state before the inevitable first to tell you about synchronized this key word

Multithreaded Java Chapter (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.