Basic operation of the thread

Source: Internet
Author: User
Tags instance method thread class volatile

Initial thread:
1. New Thread
1) Inherit thread Class 2) Implement Runnable interface
2. Thread termination
Don't use the Stop () method to stop a thread unless you know exactly what you're doing. Because the Stop () method is too violent, forcing the execution to half of the thread termination may cause some data inconsistencies. By defining the tag variable STOPME, when stopme=true, returns the result or jumps out of the loop within run.
3. Thread interruption
Thread interruption is an important thread-collaboration mechanism. Strictly speaking, a thread break does not cause the thread to exit immediately, but instead sends a notification to the thread informing the target thread that someone wants you to quit! As to how the target thread is handled after receiving the notification, it is entirely up to the target thread to decide.
There are three ways to thread interrupts in the thread class:

Note: the Thread.Sleep () method throws an exception because of an interrupt, at which point it clears the interrupt token, and if not, the interrupt is not captured at the start of the next loop, so the interrupt mark bit is set again in the exception handling.
public static void Main (string[] args) throws Interruptedexception {
T1=new thread () {
Geneva @Override
public void Run () {
while (true) {
if (Thread.CurrentThread (). isinterrupted ()) {
System.out.println ("interruted!");
a break;
Ten try {
Thread.Sleep (2000);
The catch (Interruptedexception e) {
System.out.println ("interruted when Sleep");
14//Set interrupt status
Thread.CurrentThread (). interrupt ();
Thread.yield ();
T1.start ();
Thread.Sleep (2000);
T1.interrupt ();
4. Waiting (wait) and notification (notify)
The object class provides two important interfaces, and the thread waits for the Wait () method and notifies the Notify () method, not the method in the thread class.
When thread A calls the Obj.wait () method, thread a stops executing and goes to a wait state. Wait till the end? Thread A waits until the other thread calls the Obj.notify () method. At this point, the Obj object becomes an effective means of communication between multiple threads.
Note: Both the object.wait () and the Thread.Sleep () methods allow the thread to wait for several times. In addition to the wait () can be awakened, another major difference is that the wait () method releases the lock on the target object, and the Thread.Sleep () method does not release any resources.
Wait and notify () must also obtain a monitor for object before calling.
5. Suspend (suspend) and resume (resume) threads
The API that belongs to thread is deprecated, because suspend () does not release any lock resources while causing the thread to pause. At this point, any other thread that wants to access a lock that is taken up by it will be implicated, causing it to continue running normally. Until the resume () operation is performed on the corresponding thread, the suspended thread can continue, and all other threads that are blocking the associated lock may continue to execute. However, if the resume () operation is executed unexpectedly before suspend (), the suspended thread may have a difficult chance of being executed.
6. Wait for thread to end (join) and humility (yield)
At this point, the thread will need to wait for the dependent thread to finish before it can continue execution. The JDK thread provides a join () operation to implement this function,

The first join () method indicates an infinite wait, which blocks the current thread until the target thread finishes executing. The second method gives a maximum wait time, and if the target thread is still executing over a given time, the current thread will continue to execute because it "can't wait".

The essence of Join () is to have the calling thread wait () on the current thread object instance, and it is important to note that you do not use methods such as Wait () or notify () on the thread object instance in your application, as this is likely to affect the work of the system API. or be affected by the system API.

Another interesting method is Thread.yield (), which is defined as follows: public static native void yield ();
This is a static method that, once executed, causes the current thread to yield the CPU. Note, however, that giving up the CPU does not indicate that the current thread is not executing. The current thread is also competing for CPU resources after it has yielded the CPU, but whether it can be assigned again is not necessary. Therefore, the call to Thread.yield () is like saying: I have done some of the most important work, I should be able to rest, can give other threads some job opportunities! If you think a thread is less important, or has a very low priority, and is afraid it will take up too much CPU resources, you can call Thread.yield () at the appropriate time to give other threads the opportunity.

Categorized management: Thread groups
Threadgroup TG = new Threadgroup ("TG");
thread T1 = new Thread (TG, new Threadgroupname (), "T1");
Tg.activecount ();
Tg.list ();
We recommend that you give them a nice name when creating threads and thread groups, so that they are easy to debug.

Back Up: Daemon thread (Daemon)
The daemon thread is a special thread, just like its name, which is the guardian of the system, silently completing some systematic services in the background, such as garbage collection threads, JIT threads can be understood as daemon threads. corresponding to the user thread, the user thread can be considered a worker thread of the system, and it will complete the business operations that the program should complete. If the user thread is all over, it also means that the program actually has nothing to do. The object that the daemon is guarding is no longer there, and the entire application should naturally end. Therefore, in a Java application, the Java virtual machine naturally exits when only the daemon thread is in use.

Do what's important first: thread priority
In Java, use 1 to 10 to indicate thread priority. You can generally use the three static scalars that are built into the thread:
Public final static int min_priority = 1;
Public final static int norm_priority = 5;
Public final static int max_priority = 10;
The larger the number, the higher the priority, but the valid range is between 1 and 10. The following code shows the role of precedence. High-priority threads tend to be faster to complete.

The concept of thread safety and synchronized
Thread safety is the root and foundation of parallel programs.
We also remember that multithreaded read-write Long data case! This is a typical counter-example. However, this error has improved after the use of the volatile keyword. However, volatile does not really guarantee thread safety. It can only ensure that one thread modifies the data and other threads can see the change. However, when two threads modify a data at the same time, there is still a conflict.
The use of synchronized
? Specifies the Lock object: Locks the given object to obtain a lock on the given object before entering the synchronization code.
Directly acting on the instance method: it is equivalent to lock the current instance and get the lock of the current instance before entering the synchronization code.
Directly acting on a static method: the equivalent of locking the current class, before entering the synchronization code to obtain the current class lock.

In addition to threading for thread synchronization and ensuring thread safety, syn-chronized can also guarantee visibility and ordering between threads. From the perspective of visibility, synchronized can completely replace the function of volatile, but it is not so convenient to use. In terms of order, because synchronized restricts only one thread to access the synchronization block at a time, the execution results are always the same, regardless of how the code within the synchronization block is executed in a disorderly sequence, as long as the serial semantics are guaranteed to be consistent. While other access threads must be able to access the code block to read the data after acquiring the lock, the final result they see does not depend on the execution of the code, so that the order problem is naturally resolved (in other words, multiple threads that are synchronized restricted are serially executed).

In Java, an integer belongs to an immutable object. That is, once an object is created, it cannot be modified. That is, if you have an integer representing 1, then it will always represent 1, and you cannot modify the integer value to make it 2. What if you need 2? Also very simple, create an integer and let it represent 2.
Using Javap de-compilation i++ actually uses the Integer.valueof () method to create a new integer object and assigns it to the variable i. In other words, the i++ in real execution: i=integer.valueof (I.intvalue () +1);
Further viewing integer.valueof (), we can see: public static Integer valueOf (int i) {assert integercache.high >= 127; if (I >= integ Ercache.low && i <= integercache.high) return integercache.cache[i + (-integercache.low)]; return new Integer (i);}

Use the Jstack tool to display the thread information for the program, as shown below. Where JPS can display all Java processes in the current system. Instead, Jstack can print the internal thread and its stack for a given Java process.

C:\Users\geym >jps
14240 Hashmapmultithread
1192 Jps
C:\Users\geym >jstack 14240

Basic operation of the thread

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