Java syntax Summary-Thread

Source: Internet
Author: User

Java syntax Summary-Thread

It seems very troublesome and complicated to mention threads. In fact, it is true that programming involving threads is very skillful. This requires us to change our mindset, understand the more common skills of the thread mechanism, and write highly efficient programs that do not depend on a JVM implementation. After all, in Java alone, the implementations of virtual machines are different. I was most impressed by the uncertainty and lack of security when I learned the thread. The running of each thread was fully promoted in an unpredictable way and at a speed. Some of them ran the program for N times, the results are very different.


1. What is a thread? Threads are subtasks that are independent from each other and can run independently. Each thread has its own call stack. The so-called multi-task is to switch the CPU time slice to different sub-tasks cyclically. Although from a micro perspective, a single-core CPU runs only one sub-task at the same time, from a macro perspective, each subtask appears to be running continuously at the same time. (However, the JAVA thread is not allocated by time slice. At the end of this article, we reference the understanding of the thread in the original JAVA Article translated by a netizen .)

2. in java, a Thread refers to two different contents: one is an object of the java. lang. Thread class, and the other can be the Thread execution. Like other objects, thread objects are created, run, and killed on stacks. But the difference is that thread execution is a lightweight process with its own call stack.
In this case, each call stack corresponds to one thread, and each thread corresponds to another call stack.
When we run a java program, there is an entry function main (), whose corresponding thread is called the main thread. Once a new thread is created, a new call stack is generated, which is detached from the original main thread, that is, concurrent execution with the main thread.


4. When it comes to threads, it is rarely guaranteed. We must understand what is a guaranteed operation and what is an insecure operation, so that the designed program can work well in various JVMs. For example, in some jvm implementations, java threads are mapped to local operating system threads. This is part of the core of java.

5. Create a thread.
There are two ways to create a thread:
A. inherit from the java. lang. Thread class.
Class ThreadTest extends Thread {
Public void run (){
System. out. println ("someting run here! ");
}
Public void run (String s ){
System. out. println ("string in run is" + s );
}
Public static void main (String [] args ){
ThreadTest tt = new ThreadTest ();
Tt. start ();
Tt. run ("it won't auto run! ");
}
}

The output results are interesting:
String in run is it won't auto run!
Someting run here!
Note the order of output: It seems that the order is the opposite! Why?
Once the start () method is called, you must give the JVM time to configure the process. Before the configuration is complete, the overloaded run (String s) method is called, and the result is "string in run is it won't auto run !", The tt thread completes the configuration and outputs "someting run here !".
This conclusion is relatively easy to verify:
Modify the above program in tt. start (); followed by the statement for (int I = 0; I <10000; I ++); in this way, the main thread starts to execute a for loop with a large amount of computing, the tt. run ("it won't auto run! "); Statement. At this time, the tt thread and the main thread are executed in parallel, and there is enough time to complete the thread configuration! So let's take a first step! The modified program running result is as follows:
Someting run here!
String in run is it won't auto run!
Note: The order of output results is not guaranteed! Don't rely on this conclusion!

The run () method without parameters is automatically called, while the run () method with parameters is overloaded and must be explicitly called.
The limitation of this method is: This method is very simple, but it is not a good solution. If the Thread class is inherited, other classes cannot be inherited. java is a single inheritance structure and the inheritance opportunity should be left to other classes. Unless you have more operations unique to the thread.
There are many Thread management methods in the Thread class, including creating, starting, and pausing them. All operations start from the run () method and write the code that needs to be executed in an independent thread in the run () method. The run () method can call other methods, but the execution thread always calls run ().

B. Implement the java. lang. Runnable interface.
Class ThreadTest implements Runnable {
Public void run (){
System. out. println ("someting run here ");
}
Public static void main (String [] args ){
ThreadTest tt = new ThreadTest ();
Thread t1 = new Thread (tt );
Thread t2 = new Thread (tt );
T1.start ();
T2.start ();
// New Thread (tt). start ();
}
}

It is a little more complex than the first method. In order to make the code run independently, a Thread object is also required. In this way, the Code related to the thread is separated from the code to be executed by the thread.

Another method is to create an anonymous internal class in the form of parameters, which is also common.
Class ThreadTest {
Public static void main (String [] args ){
Thread t = new Thread (new Runnable (){
Public void run (){
System. out. println ("anonymous thread ");
}
});

T. start ();
}
}
If you do not catch up with this method, please refer to the internal class I have summarized.

The first method is to create a thread using a non-argument constructor. When the thread starts to work, it will call its own run () method.
The second method is to use a constructor with parameters to create a thread, because you need to tell this new thread to use your run () method instead of its own.
In the preceding example, a target can be assigned to multiple threads, which means that several execution threads will run identical jobs.

6. When is the thread active?
Before the start () method is called to start the thread, the thread status is not active. The test procedure is as follows:
Class ThreadTest implements Runnable {
Public void run (){
System. out. println ("someting run here ");
}
Public static void main (String [] args ){
ThreadTest tt = new ThreadTest ();
Thread t1 = new Thread (tt );
System. out. println (t1.isAlive ());
T1.start ();
System. out. println (t1.isAlive ());
}
}

Result output:
False
True
The isAlive method is the best way to determine whether a thread has been started and the code in the run () method has not been completed.

7. Start a new thread.
The start () method must be called to start a thread. Only in this way can a new call stack be created. Directly calling the run () method will not create a new call stack, nor create a new thread. The run () method is no different from the normal method!

8. Give a meaningful name to the thread.
If this Thread is not named, the Thread will have a default name in the format of "Thread-" and the Thread serial number, for example, Thread-0.
This looks unreadable and cannot tell from the name what functions the thread has. The following describes how to name a thread.
First: Use the setName () function
Type 2: Use a constructor with a thread name
Class ThreadTest implements Runnable {
Public void run (){
System. out. println (Thread. currentThread (). getName ());
}
Public static void main (String [] args ){
ThreadTest tt = new ThreadTest ();
// Thread t = new Thread (tt, "eat apple ");
Thread t = new Thread (tt );
T. setName ("eat apple ");
T. start ();
}
}

9. "insecure" multi-thread operation. The following code may be impressive.
Class ThreadTest implements Runnable {
Public void run (){
System. out. println (Thread. currentThread (). getName ());
}
Public static void main (String [] args ){
ThreadTest tt = new ThreadTest ();
Thread [] ts = new Thread [10];

For (int I = 0; I <ts. length; I ++)
Ts [I] = new Thread (tt );

For (Thread t: ts)
T. start ();
}
}
The result of running on my computer is:
Thread-0
Thread-1
Thread-3
Thread-5
Thread-2
Thread-7
Thread-4
Thread-9
Thread-6
Thread-8
And the results of each run are different! If you continue to reference the previous example, the running of the thread is mostly not guaranteed. This guarantee means that the running of a thread is completely controlled by the scheduling program. We cannot control the execution sequence of the thread, and the duration is not guaranteed, with unpredictable results.


10. thread status.
A. New status.
Instantiate the Thread object, but it is not in the status when the start () method is called.
ThreadTest tt = new ThreadTest ();
Or Thread t = new Thread (tt );
At this time, although Thread objects have been created, as described above, they are not active and cannot be tested by isAlive.

B. readiness status.
The thread is eligible to run, but the scheduler has not yet elected it as the status of the running thread. That is to say, you have met the running conditions and can run the task immediately after it is selected.
It is also the status after the start () method is called but not running. At this time, although it is not running, it is considered to be active and can be tested through isAlive. In addition, after the thread runs, or is blocked, waiting, or sleep, the thread enters the ready state first.

C. Running status.
Select the status of the thread when the current execution process is selected from the ready state pool (not a queue, but a pool.

D. Waiting, blocking, and sleep.
The three States have one thing in common: the thread is still active, but without running conditions, once a thread is ready, it can be changed to the ready state (not directly to the running state ). In addition, the suspend () and stop () methods have been deprecated, which is dangerous and should not be reused.

E. Death status.
When the run () method of a thread ends, the thread completes its historical mission and its stack structure will be dissolved, that is, it will die. But it is still a Thread object, and we can still reference it, just like other objects! It will not be recycled by the garbage collector, because the reference to this object still exists.
In this case, even if the run () method stops running, the thread is not dead! The fact is that once a thread dies, it will never be restarted. That is to say, it cannot be run again using the start () method! In this case, the IllegalThreadStateException will be thrown. For example:
T. start ();
T. start ();
Give up, artificial respiration or pacemaker doesn't help ...... The thread is also a disposable item.

11. Stop the thread from running.
A. Sleep. Sleep () method
There are many reasons for a thread to sleep. For example, if the thread runs too fast, it needs to be slowed down to coordinate with other threads. When querying the stock price at that time, the thread queries every five minutes, it can save bandwidth, and the real-time requirement is not that high.
Thread. sleep (5*60*1000) can be implemented using the static method of Thread; sleep for 5 minutes. The sleep parameter is millisecond. However, the sleep () method throws an InterruptedException check exception. For this check exception, we must either declare or use a handler.
Try {
Thread. sleep (20000 );
}
Catch (InterruptedException ie ){
Ie. printStackTrace ();
}
Now that we have the sleep () method, can we control the thread execution sequence! Are you able to sleep after each thread completes execution? In this way, we can control the running sequence of threads. The following is an example in the book:
Class ThreadTest implements Runnable {
Public void run (){
For (int I = 1; I <4; I ++ ){
System. out. println (Thread. currentThread (). getName ());
Try {
Thread. sleep (1000 );
} Catch (InterruptedException ie ){}
}
}
Public static void main (String [] args ){
ThreadTest tt = new ThreadTest ();
Thread t0 = new Thread (tt, "Thread 0 ");
Thread t1 = new Thread (tt, "Thread 1 ");
Thread t2 = new Thread (tt, "Thread 2 ");
T0.start ();
T1.start ();
T2.start ();
}
}

And the result is given:
Thread 0
Thread 1
Thread 2
Thread 0
Thread 1
Thread 2
Thread 0
Thread 1
Thread 2
That is, Thread 0 Thread 1 Thread 2 appears alternately in this order. Although the results seem to be the same as we expected, the results are unreliable. It was verified by my dual-core computer:
Thread 0
Thread 1
Thread 2
Thread 2
Thread 0
Thread 1
Thread 1
Thread 0
Thread 2
It seems that the thread is really unreliable. However, the sleep () method is still the best way to ensure that all threads have the chance to run. At least it ensures that a thread does not run until it is finished.

Time accuracy. Once again, the thread will not enter the running state, but the ready state. Therefore, the specified time in sleep () is not the exact time when the thread is not running! You cannot rely on the sleep () method to provide exact timing. We can see that many applications use sleep () as the timer, and there is nothing bad, but we must know that sleep () it is not accurate to ensure that the thread can immediately enter the running state when it wakes up.

The sleep () method is a static method, which refers to the number of milliseconds in which the currently executed thread is sleeping. It is unnecessary to see Thread. currentThread (). sleep (1000); in some books. Thread. sleep (1000. Similar to the getName () method, it is not a static method. It must target a specific Thread object. In this case, use the method Thread. currentThread (). getName () to obtain the current Thread ();

B. thread priority and concession.
The priority of the thread. In most jvm implementations, the scheduler uses a preemptive scheduling mechanism based on the thread priority. If a thread enters the runable State and has a higher priority than any other thread in the pool and the currently running process, the thread with a lower priority enters the runable state, the thread with the highest priority is selected for execution.

The conclusion is that the priority of the currently running thread is generally not lower than that of any thread in the pool. However, not all jvm scheduling is like this, so it cannot rely on the thread priority to ensure the correct operation of the program. This is still not guaranteed, the thread priority should be used as a method to improve program efficiency, and this method cannot depend on the priority operation.

Another unguaranteed operation is that when the currently running thread has the same priority as the thread in the pool or the thread in the pool has the same priority, the scheduling Implementation of JVM selects the thread it prefers. You may choose to run the task until it is completed. Or you can use the time slice allocation method to provide equal opportunities for each thread.

The priority is set by a positive integer, usually 1-10. The JVM never changes the priority of a thread. By default, the priority is 5. The Thread class has three static final constants defining the Thread priority range: Thread. MIN_PRIORITY (1) Thread. NORM_PRIORITY (5) Thread. MAX_PRIORITY (10)

Static Thread. yield () method.
It is used to bring the current running thread back to the running state, so that other threads with the same priority can run. The purpose of the yield () method is to allow threads with the same priority to rotate properly. However, this effect cannot be ensured! Because, even if the current status becomes runable, it may be selected again by JVM! That is, re-election.

Non-static join () method.
Add a thread to the end of another thread. Adding thread B to thread A means that thread B will not enter the runable state before thread A is finished.
Thread t = new Thread ();
T. start ();
T. join;
This code is used to obtain the current thread and add it to the end of the t thread. After the t thread finishes running, the original thread continues to run. The examples in the book have a bad effect on my computer and I cannot see any results. Maybe the CPU is too fast and dual-core; maybe the reason for JDK1.6?

12. The summary is not completed. This part of thread is very important, and there are a lot of content. It is too fast and easy to digest, even slowly digest ......

Appendix: Explanation of threads in the original java.

E text:

Thread Scheduling

In Java technology, threads are usually preemptive, but not necessarily Time-sliced (the process of giving each thread an equal amount of CPU time ). it is common mistake to believe that "preemptive" is a fancy word for "does time-slicing ".

For the runtime on a Solaris Operating Environment platform, Java technology does not preempt threads of the same priority. however, the runtime on Microsoft Windows platforms uses time-slicing, so it preempts threads of the same priority and even threads of higher priority. preemption is not guaranteed; however, most JVM implementations result in behavior that appears to be strictly preemptive. except ss jvm implementations, there is no absolute guarantee of preemption or time-slicing.The only guarantees lie in the coder's use of wait and sleep.

The model of a preemptive schedtive is that specified threads might be runnable, but only one thread is actually running. this thread continues to run until it ceases to be runnable or another thread of higher priority becomes runnable. in the latter case, the lower priority thread is preempted by the thread of higher priority, which gets a chance to run instead.

A thread might cease to runnable (that is, because blocked) for a variety of reasons. the thread's code can execute a Thread. sleep () call, deliberately asking the thread to pause for a fixed period of time. the thread might have to wait to access a resource and cannot continue until that resource become available.

All thread that are runnable are kept in pools according to priority. when a blocked thread becomes runnable, it is placed back into the appropriate runnable pool. threads from the highest priority nonempty pool are given CPU time.

The last sentence is worded loosed because :( 1) In most JVM implementations, priorities seem to work in a preemptive manner, although there is no guarantee that priorities have any meaning at all; (2) microsoft Window's values affect thread behavior so that it is possible that a Java Priority 4 thread might be running, in spite of the fact that a runnable Java Priority 5 thread is waiting for the CPU. in reality, required JVMs implement pool as queues, but this is not guaranteed hehavior.

Versions Translated by netizens:
In java technology, threads are usually preemptible without the need for time slice allocation processes (processes allocated to each thread with equal cpu time ). A common mistake is that "preemption" is "allocating time slices ".
In the running environment on the Solaris platform, threads with the same priority cannot seize the cpu time of each other. However, in the windows operating environment where time slice is used, you can seize the cpu time of threads with the same or higher priority. Preemption is not absolute, but most JVM implementation results show strict preemption in behavior. Looking at the implementation of JVM, there is no absolute preemption or time slice, but it depends on the use of the encoding methods wait and sleep.
In the preemptible scheduling model, many threads are in a running (waiting) state, but only one thread is running. This thread is always running until it is terminated and enters the running state (waiting state) or another thread with a higher priority changes to the running state. In the latter case, the thread with the lower priority is preemptible by the thread with the higher priority, and the thread with the higher priority gets the chance to run.
The thread can be terminated and run for various reasons (because of congestion ). For example, the Thread code can execute the Thread. sleep () method when appropriate to deliberately stop the Thread; the Thread may have to wait until the resource is available to access the resource.
All running threads are kept in different pools based on their priorities. Once a blocked thread enters the runnable state, it will be put back into the appropriate runable pool. The threads in the pool with the highest non-null priority will obtain the cpu time.
The last sentence is inaccurate because:
(1) In most JVM implementations, although there is no guarantee that the priority has any significance, the priority seems to work in preemption mode.
(2) Microsoft windows evaluates the impact of thread behavior, even though a java thread with a running priority of 5 is waiting for cpu time, however, a java thread with a priority of 4 may be running.
In fact, many JVMs use queues to implement the pool, but the behavior is not guaranteed.


 

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.