Java Multithreading and Promotion (i)

Source: Internet
Author: User

Java Multithreading and progression (i) concept and principle of Java threading, the concept of thread and process in the operating system

A process is an application running in the operating system memory in which each process has its own separate piece of memory space, in which multiple threads can be started in a process.

A thread is an execution process in a process that can run multiple threads in a process. For example, a java.exe process can run many threads. Threads are always part of a process, and multiple threads in a process share the memory of the process.

Simply put, a process is a single execution of an application on the operating system, and a thread is an execution process in the process, and the process contains multiple threads running.

Second, the Java thread

An instance of the thread class is just an object, like any other object in Java, that lives and dies on the heap.

note that because each thread is executing a different method, each thread will have its own Java stack , without interfering with it.

Iii. creation and startup of Java threads (1) inheriting the thread class

Mode 1-inherits the thread class and makes the Class A member of the thread threading system. It is not recommended to use this approach from the nature of inheritance.

class SubThread extends  Thread {    @Override    public void run() {        // ...代码    }}SubThread sub = new SubThread();sub.start(); // 启动线程

Mode 2-anonymous classes that inherit from thread are also not recommended for use

// 继承自Thread的局部匿名类new Thread() {    @Override    public void run() {        // 代码    }}.start();
(2) Implement Runnable interface

Mode 1

class SubThread implements  Runnable {    @Override    public void run() {        // ...代码    }}Thread t = new Thread(new SubThread());t.start(); // 启动线程

Mode 2

new Thread(new Runnable() {    @Override    public void run() {        // 代码    }}).start();
(3) inherit the thread class and implement the Rrunnable interface
new Thread(new Runnable() {    @Override    public void run() {        // 代码        System.out.println("runnable run");    }}) {    @Override    public void run() {        // 代码        System.out.println("thread run");    }}.start();// 结果 thread run
(4) Start thread

To start a thread, call the method on the thread object start() , not the run() method.

Before calling the start() method, the thread is still in the new state, and the new one refers to having a thread object, but not yet a real thread.

After the start() method is called, a thread is actually started (and a stack is created at the same time), and the state of the thread is moved from the new to the operational state , and the target method runs when the thread acquires the execution Opportunity run() .

Iv. Considerations for Threading
    1. The name of the thread, a running thread always has a name, the name has two sources, one is the name of the virtual machine itself, and one is your own set name. In the absence of a specified thread name, the virtual machine always assigns a name to the thread, and the main thread's name is always Mian, and the name of the non-main thread is thread-x.

      指定线程名99:线程99        // 通过Thrad的构造方法为线程赋予名称默认线程名:main默认线程名:Thread-0
    2. The method to get the current thread object is: Thread.CurrentThread ();, the method to get the name is: Thread.CurrentThread (). GetName ();

    3. In the following code, you can only guarantee that each thread will start and each thread will run until it is complete. A series of threads starting in some order does not mean that they will be executed in that order. For any set of startup threads, the scheduler does not guarantee its execution order and the duration is not guaranteed.

      new Thread(new Runnable() {    @Override    public void run() {        // 代码    }}).start();new Thread(new Runnable() {    @Override    public void run() {        // 代码    }}).start();
    4. When the thread target run () method ends, the thread finishes.

    5. Once the thread is started, it can never be restarted again. Only one new thread can be started, and only once. A running thread or a dead thread can be restarted.
    6. The scheduling of threads is part of the JVM, and on a CPU machine, you can actually run only one thread at a time. Only one thread stack executes at a time. The JVM thread scheduler determines which threads are actually running in a running state.
V. Transition of thread State

The state transition of a thread is the basis of thread control.

The total thread state can be divided into five states: newborn, death, can run, run, wait/block. This is described in a diagram as follows:

    1. Freshman (new): A new Thread object was created.

    2. Runnable: After the thread object is created, other threads (such as the main thread) call the object's start () method. The thread in this state is in a pool of running threads, waiting for the thread to be dispatched to get the CPU right.

    3. Run (running): the thread that can run the state (runnable) obtains the CPU time slice (TimeSlice) and executes the program code.

    4. Block: Blocking state refers to a thread that, for some reason, abandons the use of the CPU, letting the CPU TimeSlice and temporarily stop running. Until the thread enters the operational (runnable) state, there is a chance to get the CPU TimeSlice again to the run (running) state. There are three types of blocking:

      (i). Wait for blocking: the thread that is running (running) executes the o.wait () method, and the JVM puts the thread into the waiting queue (the waitting queues).

      (b). Synchronous blocking: When a thread running (running) acquires a synchronization lock on an object, if the synchronization lock is occupied by another thread, the JVM puts the thread into the lock pool.

      (iii). Other blocking: The thread that runs (running) executes the thread.sleep (long ms) or T.join () method, or when an I/O request is made, the JVM will place the thread in a blocked state. When the sleep () state time-out, join () waits for the thread to terminate or times out, or the I/O process is complete, the thread is re-transferred to the operational (runnable) state.

    5. Death (dead): The thread Run (), the main () method finishes executing, or the run () method exits because of an exception, the thread ends the life cycle. The thread of death cannot be resurrected again.

Notable:

  1. When the method is called, the obj.wait() current thread waits, and the current thread must have a lock (which is not nonsense), which causes its own hibernation (which frees the lock that the thread owns ) and places itself (the thread) in the waiting queue . When this thread is awakened, the thread is removed from the object's waiting set and the thread is dispatched again. The thread then competes with other threads in a normal way to gain the right to synchronize on that object, and once control of the object is obtained, all its synchronous declarations on that object are restored to the previous state, which is the case when the wait method is called. The thread then returns from the call to the wait method. Therefore, when returning from the wait method, the synchronization state of the object and this thread is exactly the same as when the wait method was called.

  2. more attention (a lot of beginners will make mistakes), put the wait() method in if() , so that the operation may lead to security problems, we should keep the thread to be reminded of the condition of the test, if not meet the condition, then continue to wait, in other words, The wait should always occur in the loop, as in the following example:

    synchronized (obj) {     while (<condition does not hold>)     obj.wait(timeout);     // Perform action appropriate to condition  }
  3. Thread.sleep();method does not release locks that are owned by this thread. At the same time, thread sleep is the best way to help all threads get the chance to run, and when the thread wakes up, it goes back to the operational state instead of the running state .

Java Multithreading and Promotion (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.