Java syntax Summary-Thread

Source: Internet
Author: User
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.

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 ......
 

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.