"52" Java Multithreaded anatomy

Source: Internet
Author: User

Thread state: Threads have the following 4 states: New State (new):

A new thread object is created, and when you create a thread with new, the thread is not running.

Ready state (Runnable):

After the thread object is created, other threads call the object's start () method. The state of the thread is located in a pool of running threads that becomes operational and waits for the CPU to be used.

Operating State (Running):

The ready state of the thread gets the CPU and executes the program code.

Blocking state (Blocked):

A blocking state is a time when a thread abandons the CPU for some reason and temporarily stops running. Until the thread is in a ready state, the opportunity to go to the running state is reached.

There are three types of blocking:

A. Wait for blocking: The running thread executes the wait () method, and the JVM puts the thread into the waiting pool.
B. Synchronous blocking: When a running thread acquires a synchronization lock on an object, the JVM puts the thread into a lock if the synchronization lock is occupied by another thread.
C. Other blocking: The running thread executes the sleep () or join () method, or when an I/O request is made, the JVM will place the thread in a blocked state. When the sleep () state times out, join () waits for the thread to terminate or time out, or the I/O process finishes, the thread is re-entered in a ready state.

Death status (Dead):

A. Natural death due to the normal exit of the Run method;
B. Unexpected event not caught terminating execution of the Run method, resulting in sudden thread death

Such as:

Priority of the thread

Each Java thread has a priority, which helps the operating system determine the order in which the threads are dispatched.
The priority of a Java thread is an integer whose value range is 1 (thread.min_priority)-Ten (thread.max_priority).
By default, each thread will be assigned a priority of norm_priority (5).
A thread with a higher priority is more important to the program, and the processor resources should be allocated before a low-priority thread. However, thread precedence does not guarantee the order in which threads are executed, and is very dependent on the platform.

To determine whether a thread is currently alive, you can use the IsAlive method.

If the thread is a running thread or is interrupted, the method returns True if the thread is still a new thread, or if the thread is a dead thread, then the method returns false

Changes in the state of a thread under different circumstances.

How to implement Java multithreading

1. Inherit the thread class
2. Implement Runnable interface
3, the use of Executorservice, callable, the future to achieve a return result of multi-threading.

There are no return values for the first two methods after the thread has finished executing, only the last one with the return value. One of the most common is the first two implementations.

Runnable and thread implementations of multithreading differ runnable interfaces have the following advantages over inheriting the thread class:

1, can avoid the Java single inheritance characteristics brought about by the limitations;

2, enhance the robustness of the program, code can be shared by multiple threads, code and data is independent;

3. Suitable for multiple threads with the same program code to handle the same resource situation.

The following is an example of a typical ticket purchase procedure (which is basically the case) to illustrate the difference between the two.
 class MyThread extends Thread{      Private intTicket =5; Public voidRun () { for(intI=0;i<Ten; i++) {if(Ticket >0) {System.out.println ("ticket ="+ ticket--); }          }      }  } Public  class threaddemo{       Public Static voidMain (string[] args) {NewMyThread (). Start ();NewMyThread (). Start ();NewMyThread (). Start (); }


As can be seen from the results, each thread sold 5 tickets Separately, that is, to complete the task of buying tickets independently, but in practical applications, such as railway station ticketing, need multiple threads to work together to complete the task, in this case, multiple threads together buy 5 tickets.

The following is a multithreaded program implemented by implementing the Runnable interface, with the following code:
 class MyThread implements Runnable{      Private intTicket =5; Public voidRun () { for(intI=0;i<Ten; i++) {if(Ticket >0) {System.out.println ("ticket ="+ ticket--); }          }      }  } Public  class runnabledemo{       Public Static voidMain (string[] args) {MyThread my =NewMyThread ();NewThread (My). Start ();NewThread (My). Start ();NewThread (My). Start (); }  }


As can be seen from the results, three threads sold a total of 5 tickets, that they jointly completed the task of buying tickets, to achieve the sharing of resources.

Summary of differences:

1. In the second method (Runnable), the order of ticket output is not 54321, because the timing of thread execution is unpredictable, and ticket– is not an atomic operation.

2, in the first method, we new 3 thread objects, that is, three threads execute the code in three objects, so it is three threads to complete the task of selling tickets independently, and in the second method, we also new 3 thread objects, but only one runnable object, 3 thread objects share the code in this Runnable object, so there will be 3 threads that work together to complete the result of the sell ticket task. If we new out 3 runnable objects, passing in 3 thread objects as arguments, then 3 threads will execute the code in their respective runnable objects independently, i.e. 3 threads sell 5 tickets respectively.

3, in the second method, because 3 thread objects together execute a runnable object in the code, it may cause the thread is unsafe, such as May ticket output 1 (if we system.out .... Before the statement plus the thread hibernation operation, This situation is likely to occur because, after a thread has judged ticket to be 1>0, there is no time to lose 1, and another thread has reduced the ticket by 1 to 0, then the previous thread will ticket minus 1, then get-1. This requires the addition of a synchronous operation (that is, a mutex) to ensure that only one thread at a time performs the operation in each for loop. In the first approach, there is no need to join the synchronization operation because each thread executes the code in its own thread object, and there is no case where multiple threads are executing the same method together.

After introducing the above examples, we have the following differences between the sleep (), wait (), Yeid (), join () methods to summarize the difference between the sleep method and the Wait method:

The 1.sleep method is a static method, and the wait method is a non-static method.
The 2.sleep method wakes itself up after the time, but wait cannot, and the other thread must let it "wake up" by the Notify (all) method.
The 3.sleep method is typically used in cases where there is no need to wait for resources, such as waiting for threads, database connections, and wait.

The difference between sleep/wait and Yeld methods:

After the sleep or wait method is called, the thread enters the block state, and the thread enters the runnable state after the Yeld method is called.

The difference between the wait and join methods:

The 1.wait method represents a mutually exclusive relationship between threads, and the join method embodies the synchronization relationship between threads.
The 2.wait method must be unlocked by another thread, and the join method does not require that the current thread automatically become ready as long as the waiting thread finishes executing.
One use of the 3.join method is to have the thread wait until all the child threads have finished executing the business logic before the child threads are done.

Welcome to the group: public number It face questions summary discussion group

If the scan does not go in, add me (rdst6029930) pull you. Sweep my QR code plus me

You are welcome to pay attention to the "It question summary" subscription number. Every day to push the classic face test and interview tips, are dry! The QR code of the subscription number is as follows:

Reference:
Http://www.runoob.com/java/java-multithreading.html
http://blog.csdn.net/ns_code/article/details/17161237
http://wangqiang6028.iteye.com/blog/1887342

"52" Java Multithreaded anatomy

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.