Java multi-thread Learning (3) -- thread stack and java multi-thread learning thread

Source: Internet
Author: User

Java multi-thread Learning (3) -- thread stack and java multi-thread learning thread

I. Thread stack Model

The thread stack model is the basis for understanding Thread Scheduling principles and thread execution processes. The thread stack refers to the stack information of Thread Scheduling in the memory at a certain time point. The method currently called is always at the top of the stack. The content of the thread stack changes with the change of the running state of the thread, to study the thread stack, You must select a runtime (where the code runs)


Stack A in is the running stack information of main thread. When new JavaThreadDemo () is executed (). threadMethod (); method, the threadMethod method is located at the top of the stack in the main thread stack, and a new thread is created for the start () method running in the threadMethod method, the newly created thread will also have its own thread stack B. You can see that the stack information is changing at different runtime times, and the change of stack A can be seen from it. In this case, stack A and stack B run concurrently, and the main thread and the newly created thread run concurrently. We can see the difference between method call and thread start. The method call is only the code that calls the method in the original thread stack, and the thread starts to create a new thread stack of its own to run its own thread.

Ii. Thread Lifecycle

The life cycle of a thread includes five states: new, runable, running, blocked, and dead.


New: A New thread object is created, but the start () method in the thread has not been called. The thread is in the new State.

Runable status: Call the start () method of the thread, and the thread enters the runable status. At this time, the thread waits for the JVM scheduler to execute. That is to say, I have prepared and can go to the battlefield, wait for only one opportunity to change to the running status.

Running status: the thread scheduler selects a thread from a large number of runable threads to run. It is like the coach chooses a future competition. This is the only way for a thread to enter the running state, which must be scheduled by JVM.

Blocking status: the waiting, sleep, and blocking status of a thread are collectively called blocking. At this time, the thread is still active and on standby. When a condition is found, the thread can return a running status.

Dead state: When the run () method of the thread is completed, the thread ends. At this time, the thread does not exist and all the resources it occupies will be recycled.


Iii. Thread Blocking

There are multiple types of thread blocking, including three common ones (I/O blocking is not discussed)

1. Sleep

2. Waiting

3. Get the thread lock and block it

Sleep Status: the sleep () method of a thread can enable a running thread to sleep. When the thread is sleeping, it does not return the runnable status. When the sleep time arrives, it returns the runnable status.

@ Overridepublic void run () {for (int I = 0; I <5; I ++) {try {Thread. sleep (50); // simulate the time-consuming operation System. out. println (name + ":" + I);} catch (InterruptedException e) {e. printStackTrace ();}}}
The call Thread's static method Thread. sleep () can sleep the Thread. The parameter is millisecond.

1. When the thread is sleep, the JVM scheduler will pause the execution of the thread and execute other running threads.

2. The sleep () method is a static Thread method that can only control the sleep of the current Thread.

3. After the thread's sleep time is reached, it will return to the running status, rather than the running status.

Thread priority and thread concession yield ()

The Thread makes concessions by calling the Thread. yield () method. The yield () method is used to pause the currently executed thread object, let out the processor resources, and let the processor execute other threads.

The thread in Java has a priority. The priority ranges from 1 to 10. The JVM thread scheduler is a priority-based preemptive scheduling mechanism. A thread with a higher priority has a higher chance of execution than a thread with a lower priority. This is not to say that a thread with a lower priority must wait until the execution of a thread with a higher priority is completed, only the ratios of the allocated resources are different. (The thread priority cannot be executed as expected in actual applications)

When threads in the thread pool have the same priority, the JVM scheduler randomly selects a thread in the runable state for execution. There may be two execution processes: (1) select a thread to run until the thread is blocked or running to death. (2) The time sharding Mechanism provides a uniform running opportunity for every thread in the thread pool.

To set the thread priority, you can call the setPriority (int) method of the thread to set the thread priority. The default thread priority is 5. The JVM will not change the priority of a thread at will, but the priority range of threads in different systems may be different. When the JVM cannot recognize 10 different priorities, JVM will merge these priorities into two or more threads. At this time, the threads with different priorities before the merge will be merged into a thread with a higher priority.

The Thread class defines three constants to define the priority range:

Maximum priority of a static int MAX_PRIORITY thread

The minimum priority of the static int MIN_PRIORITY thread

Default priority of the static int NORM_PRIORITY thread


Yield () method that makes thread concessions

The Thread. yield () method can pause the threads currently being executed, so that the processor has the opportunity to execute other threads, that is, to make concessions to the current Thread, and to give other threads the opportunity to be executed. After the thread executes the yield () method, the thread returns from the running state to the runable state, giving the thread with the same priority the opportunity to execute. The yield () method can be used for proper rotation among threads with the same priority. However, in practice, the yield () method cannot be guaranteed to be concession, because the concession thread returns to the runable state from the running state, then this thread can be selected and executed by the JVM scheduler.


Join Method

The non-static join () method of Thread adds Thread B to the tail of Thread A. Thread B can continue execution until Thread A finishes execution. This is equivalent to interrupting the execution of thread B to execute thread A first, similar to calling another function in the main () function until the execution of this function is complete, main () function.

The join method has a version with a time parameter. t. join (5000) causes the thread to wait for 5000 milliseconds. If this time is exceeded, it stops waiting and changes to a running state.


Three methods for temporarily removing a thread from the running status:

1. Call the thread's sleep () method to make the thread sleep for a period of time

2. Call the yield () method of the thread to temporarily return the thread to the runable state, so that other threads have the opportunity to execute.

3. Call the join () method of the thread to stop the execution of the current thread. The current thread can be executed only after the execution of the threads added to the current thread is completed.







Java three-thread guess

Import java. util. random; public class GuessNumber {public static void main (String [] args) {ThreadOne one = new ThreadOne (); one. start (); ThreadTwo two = new ThreadTwo ("Guess thread 1"); two. start (); ThreadTwo three = new ThreadTwo ("Guess Thread 2"); try {Thread. sleep (2000);} catch (InterruptedException e) {e. printStackTrace ();} three. start (); while (true) {// stop all threads if (two. getGuessResult (). equals ("guessed") | three. getGuessResult (). equals ("guessed") {one. stop (); two. stop (); three. stop (); break ;}}}// the topic Thread class ThreadOne extends Thread {private static int theNumber; // stores the expected number public void run () {Random random = new Random (); theNumber = random. nextInt (100); System. out. println ("Name of the question thread:" + theNumber);} // guess the public static String guessNumber (int number) {if (theNumber> number) {return "";} else if (theNumber <number) {return "";} else {return "";}}} // guess Thread class ThreadTwo extends Thread {private String threadName; private int minNum = 0; private int maxNum = 100; String guessResult = ""; public ThreadTwo (String threadName) {this. threadName = threadName;} public String getGuessResult () {return guessResult;} public void run () {while (true) {try {sleep (4000);} catch (InterruptedException e) {e. printStackTrace ();} int nowNum; Random random = new Random (); // generate the minimum and maximum values ...... remaining full text>

Java multithreading issues A, B, C three different threads A are responsible for sending data, B is responsible for network connection, C is responsible for data processing

The order of BAC is that, before starting the next thread, you need to wait for the result returned by another thread. You can work with the interface to call back and forth,
For example:
Class Main implement BListener {
Public void startTask (){
Start line B, input the listener instance, and call it back and forth;
}
// Override
Public void BTaskComplete (){
The line B is successfully executed;

Start thread;
}

}

Class B extends Thread {
Listener instances can be obtained during construction;
Public void run (){
...
After the execution is completed, the result is Listener. BTaskComplete ();

}

}
It's just a rough idea, but it's quite clear. I hope it will help you.

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.