Basic operations of threads (reading notes)

Source: Internet
Author: User
Tags object object volatile

    • New Thread
Creating a new thread is simple, as long as you create a thread object with the New keyword. and start it (). So what happens after the thread start ()? This is the key to the problem. Thread tread, there is a run () method. Start () Method will create a new thread and let the thread execute the Run () method
New Thread (); T1.start ();
It is important to note that the following code can also be compiled and run normally. But instead of creating a new thread, you call the Run method in the current thread, just as a normal method call
New Thread (); T1.run ();
Note: Do not use the run () method to open a new thread. He will only perform two methods of creating threads in the current thread, serially executing the code in Run ():
Thread T1 =NewThread () {@Override Public voidrun () {System.out.println ("Hello,i am He"); }};t1.start ();//Java8 versionThread t2 =NewThread (()-System.out.println ("Hello,i am He") ; T2.start (); Public classCreateThreadImplementsRunnable { Public Static voidMain (string[] args) {Thread T1=NewThread (NewCreateThread ());    T1.start (); }    /*** When an object implementing interface <code>Runnable</code> was used * To create a thread, start     ing the thread causes the object ' s * <code>run</code> method to being called in that separately executing     * Thread. * <p> * The general contract of the method <code>run</code> are that it could take any action wha     Tsoever. *     * @seeThread#run ()*/@Override Public voidrun () {System.out.println ("Oh, I am Runnable"); }}

The following methods are most commonly used!
    • Terminating a thread
In the JDK we found that thread provided a stop () method, but the stop method was discarded. The reason is that the method is too violent. Force the execution to half the thread to terminate. There may be some inconsistencies in the data. Because he freed up all the locks held by this thread, These locks are precisely used to maintain an object's consistency. For example, write the data in half, and forcibly terminate. Then the object will be written bad. At the same time because the lock has been released, another waiting read thread logically read the inconsistent object, the tragedy happened! If you need to stop a thread, In fact, the method is very simple,. It's up to us to decide when the thread quits.
 Public classCreateThreadImplementsRunnable {volatile BooleanSTOPME =false;  Public voidStopme () {STOPME=true; } @Override Public voidrun () { while(true) {            if(STOPME) {System.out.println ("Exit by Stop Me");  Break; }            synchronized(u) {intv = (int) (System.currenttimemillis ()/1000);                U.setid (v); Try{Thread.Sleep (100); } Catch(interruptedexception e) {e.printstacktrace ();            } u.setname (String.valueof (v));        } Thread.yield (); }    }}

    • Thread terminal in Java thread break is an important way of threading, from the surface understanding, the interruption is to let the target thread to stop the execution of meaning, in fact, not exactly this,
Strictly speaking, a thread break is not a thread that quits 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 gets notified, it is entirely up to the target thread to decide what to do, which is important! There are three methods associated with thread interrupts,
Thread T1 =NewThread (NewCreateThread ()); T1.interrupt ();//example method for middle thread breakT1.isinterrupted ();//determine if an instance method is interruptedThread.interrupted ();//determines whether the interrupt is interrupted and clears the current interrupt state static method Public classCreateThreadImplementsRunnable {@Override Public voidrun () { while(true) {            if(Thread.CurrentThread (). isinterrupted ()) {System.out.println ("Interrupted");  Break; }            Try{Thread.Sleep (2000);//instance thread sleeps 2s when thread hibernation is interrupted throwing Interruptedexception exception}Catch(interruptedexception e) {System.out.println ("Interrupted when Sleep");            Thread.CurrentThread (). interrupt ();        } Thread.yield (); }    }     Public Static voidMain (string[] args)throwsinterruptedexception {Thread T1=NewThread (NewCreateThread ());        T1.start (); Thread.Sleep (1000);//main execution interrupt after hibernation 1sT1.interrupt (); }}
    • Waiting (wait) and notifications (notify)
To support collaboration across multiple threads, the JDK provides two very important interface threads to wait for the wait () method and the Notify Notify () method, which is not in the thread class but in the object class, which means that any object can call both methods. When the Wait () method is called on an object instance, the current feed will wait on the object, such as thread A, called the Obj.wait () method, then thread A will stop executing and turn to wait, and wait for when to end?     Thread A waits until other threads call the Obj.notify () method, at which point the Obj object becomes an effective means of communicating between multiple threads. So how does wait () and notify () work? If a thread calls object.wwait () then he enters the waiting queue for the object, which may have multiple threads,     Because the system is running multiple threads waiting for an object at the same time. When Object.notify () is called, he will randomly select a thread from this waiting queue and wake it up, this option is not fair, and the thread that waits first is not the preferred choice, which is completely random. In addition to the Notify () method, object objects have a similar notifyall () method. He and notify () function basically the same, the difference is that he will wake up waiting in the queue for all the waiting threads, rather than a random one, it is important to note that the object.wait () method is not a random call. He must be included in the corresponding synchronized statement. Both wait () and notify () require a listener for the target object first,
 Public classsimplewn {Final StaticObject object =NewObject ();  Public Static classT1extendsThread { Public voidrun () {synchronized(object) {System.out.println (System.currenttimemillis ()+ ": T1 start!"); Try{System.out.println (System.currenttimemillis ()+ ": T1 Wait for Object");                Object.wait (); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (System.currenttimemillis ()+ ": T1 end!"); }        }    }     Public Static classT2extendsThread { Public voidrun () {synchronized(object) {System.out.println (System.currenttimemillis ()+ ": T2 start! Notify one thread ");                Object.notify (); System.out.println (System.currenttimemillis ()+ ": T2 end!"); Try{Thread.Sleep (2000); } Catch(interruptedexception e) {e.printstacktrace (); }            }        }    }     Public Static voidMain (string[] args) {Thread T1=NewT1 (); Thread T2=NewT2 ();        T1.start ();    T2.start (); }}
The code above turns on 2 threads T1 and T2,t1 execute Wait (), note that T1 takes the object lock before executing the wait, and then the execution waits for the T1 to stop waiting and release the object lock, T2 after acquiring the object lock before the Notify () method is executed. Execute Notify (), in order to make the effect obvious. We deliberately T2 to perform notify () and Hibernate for 2 seconds, so it is obvious that T1 is notified and tries to retrieve the object lock first.Note that both object.wait () and Thread.Sleep () Two methods can allow threads to wait for a certain number of hours. Except that wait () can be awakened, wait () executes the lock that releases the target object, and sleep () does not release any resources!
    • Waiting for thread to end (join) and humility (yield)
Most of the time, the input of one thread may still be very much the output of another or multiple threads. This thread needs to wait for the dependent thread to finish before it can continue, and the JDK provides a join () operation to implement this function.
 Public Final synchronized void Join (long Millis)throws  interruptedexceptionpublicfinal  voidthrows interruptedexception
The first method gives a maximum wait time, and if the target thread is still executing at a given time, the current thread will continue to execute because the wait is not over, and the second method represents the wireless wait. It blocks the current thread and knows that the target thread is finished. A simple join instance is provided below.
 Public classJoinmain { Public volatile Static inti = 0;  Public Static classAddthreadextendsThread { Public voidrun () { for(i = 0; i < 10000000; i++) ; }    }     Public Static voidMain (string[] args)throwsinterruptedexception {addthread at=NewAddthread ();        At.start ();        At.join ();    System.out.println (i); }}

In the main function, if you do not wait for Addthread with join (), then the resulting i is probably 0 or a very small number, but after join (), the main thread is willing to wait for Addthread to complete, followed Addthread along, so join () When returned. Addthread has been executed. So I will always be 10000000. Be careful not to use methods such as Wait () or notify on the thread object instance in your application, because creases can affect the operation of the system API or be affected by the system API! Another interesting approach is Thread.yield ();p ublic static native void yield (); This is a static method that, once executed, will let the current thread out of the CPU. Attention at the time, Giving up the CPU does not mean that the current thread is not executing. After the current thread gives up the CPU, it also competes for CPU resources, but whether it can be assigned again is not necessarily, so the call to Thread.yield () is like saying: I have done some of the most important work     . I should take a break. You can give other threads some job opportunities! If you think a thread is less important, or has a low priority, and is afraid that he will consume too much CPU resources, you can call this method when appropriate. Give other important threads more job opportunities!
    • Volatile Java uses a number of special operations or keywords to declare, tell the virtual machine, in this place, to pay particular attention, can not arbitrarily change the optimization of the target instruction. Easy to become unstable.
When you declare a variable with volatile, it is tantamount to telling the virtual machine that the variable is most likely to be modified by some program or thread. To ensure visibility, virtual machines do a special means to ensure the visibility of this variable!

Basic operations of threads (reading notes)

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.