Common methods of operation for Java threads

Source: Internet
Author: User

Goal:learn about setting and getting the name of the thread. understand the forced operation of threads. understand the sleep of a thread. understand the comity of threads. understand the interrupt operation of the thread. What it does: all of the operations methods in multi-threading are actually starting with the thread class. All operations are in the thread class. main methods of threading operations
No method name type description 1public thread (Runnable target) constructs the receive Runnable interface subclass object, instantiates the thread object 2public thread (Runnable target,string name) Constructs the receive Runnable interface subclass object, instantiates the thread object, and sets the threading name of the 3public thread (String name) constructs an instantiated thread object and sets the thread name. 4public static thread CurrentThread () normal returns the currently executing thread. 5public final String getName () normal return thread name 6public final int getpriority () normal return thread priority 7public Boolean isinterrupted () The normal judgment is whether the thread is interrupted, if it is, returns True, otherwise returns False8public final Boolean isActive () that is normal to determine whether the thread is active, or returns True if it returns false9public final void  Join () throws interruptedexception normal wait thread death 10public final synchronized void join (long Millis) throws Interruptedexception normal waits Millis milliseconds after the thread dies. 11public void run () normal execution thread 12public final void SetName () normal set thread name 13public final void setpriority (int newpriority) normal set thread priority Level 14public static void sleep (long Millis) throwsinterruptedexception normal causes the currently executing thread to hibernate millis milliseconds 15public void Start () normal starts the thread execution. 16public static void yield () normal suspends the currently executing thread once, allowing other threads to perform 17public final void Setdaemon (Boolean on) normal set a thread to run in the background 18public final void Setpriority (int newpriority) normal change thread priority 

Thread Nameget and set the thread namein the thread class, the thread name can be obtained through the GetName () method, and the name of the thread is set through the SetName () method. the name of a thread is typically set before the thread is started, but it also allows you to set a name for a thread that already exists. Allow two thread objects to have the same name, but in order to be clear, you should try to avoid the occurrence of such a situation. also, if the program does not specify a name for the thread, the system automatically assigns a name to the thread.
the name of the thread is best set before the threads start, avoiding duplicate names.
Class MyThread implements RUNNABLE{//implementation Runnable interface public void Run () {//overwrite run () method for (int i=0;i<3;i++) { System.out.println (Thread.CurrentThread (). GetName () + "run, I =" + i);//Get the name of the current thread}}};p Ublic class Threadnamedemo{public static void Main (String args[]) {MyThread MT = new MyThread ();//Instantiate runnable subclass Object New Thread (MT). Start ();//system automatically set thread name new T Hread (MT, "thread-A"). Start ();//manually set the thread name to new (MT, "thread-B"). Start ();//manually set the thread name new thread (MT). Start (); The system automatically sets the thread name new thread (MT). Start ();//The system automatically sets the thread name}};


from the performance point of view, the specified name will automatically appear, if not specified will find the thread using automatic numbering to complete, according to: Thread-0, Thread-1 sequentially numbered, in fact, there must be a static property in the class for the record number. get current threadThe program can get the currently running thread object through the CurrentThread () method.
Class MyThread implements RUNNABLE{//implementation Runnable interface public void Run () {//overwrite run () method for (int i=0;i<3;i++) { System.out.println (Thread.CurrentThread (). GetName () + "run, I =" + i);//Get the name of the current thread}}};p Ublic class currentthreaddemo{ public static void Main (String args[]) {MyThread MT = new MyThread ();//Instantiate runnable subclass Object New Thread (MT, "thread"). Start ();//Start line Process Mt.run ();//Call the Run () method}} directly;

It is found that in the program by the main method directly through the thread object called the inside of the Run () method, so the output of the result contains a "main", this thread is "Mt.run", because the invocation of this statement is done by the main method, that is, the main method itself is also a thread-the main path.question: Since the main method appears as a thread, how many threads does the Java runtime actually start? answer: At least two are activated. From the current knowledge, every time the Java program executes, it will actually start a JVM, and each JVM actually starts a process in the operating system. Java itself has a garbage collection mechanism, so the Java runtime starts at least two threads: the main thread, the GC. determines whether a thread is started
Class MyThread implements RUNNABLE{//implementation Runnable interface public void Run () {//overwrite run () method for (int i=0;i<3;i++) { System.out.println (Thread.CurrentThread (). GetName () + "run, I =" + i);//Get the name of the current thread}}};p Ublic class threadalivedemo{ public static void Main (String args[]) {MyThread MT = new MyThread ();//Instantiate runnable Subclass Object Thread t = new Thread (MT, "thread");//Real Instantiate the Thread object System.out.println ("Before thread begins execution--" + t.isalive ()); Determine whether to start T.start ();//Start thread System.out.println ("thread starts executing--" + t.isalive ()); Determines whether to start a for (int i=0;i<3;i++) {System.out.println ("main run-to" + i);} The following output is not deterministic System.out.println ("After code executes--" + t.isalive ()); Determine whether to start}};

The thread is activated when the Start method is called, and is closed when the thread finishes executing the task. If it is not completed, it is still active.forced execution of Threadsin thread operations, you can use the join () method to force a thread to run, the other threads cannot run while the threads are forced to run, and must wait for the thread to finish before it can continue to run.
Class MyThread implements RUNNABLE{//implementation Runnable interface public void Run () {//overwrite run () method for (int i=0;i<50;i++) { System.out.println (Thread.CurrentThread (). GetName () + "run, I =" + i);//Get the name of the current thread}}};p Ublic class Threadjoindemo{public static void Main (String args[]) {MyThread MT = new MyThread ();//Instantiate runnable Subclass Object Thread t = new Thread (MT, "thread");//Instantiate Threa D object T.start ();//start thread for (int i=0;i<50;i++) {if (i>10) {try{t.join ();//thread Force run}catch (interruptedexception e) {}} System.out.println ("Main thread runs--" + i);}};

The sleep of a threadallow a thread to hibernate temporarily in the program, using the Thread.Sleep () method directly.
Class MyThread implements RUNNABLE{//implementation Runnable interface public void Run () {//overwrite run () method for (int i=0;i<50;i++) {try{ Thread.Sleep (500);//thread hibernation}catch (interruptedexception e) {}system.out.println (Thread.CurrentThread (). GetName () + "run , i = "+ i);//Get the name of the current thread}}};p ublic class Threadsleepdemo{public static void Main (String args[]) {MyThread MT = new Mythrea D ();//Instantiate runnable Subclass Object Thread t = new Thread (MT, "thread");//Instantiate Thread object T.start ();//Start Thread}};
Will be found every 500 milliseconds, executed once. Interrupt of Threadwhen one thread is running, another thread can break its running state directly through the interrupt () method.
Class MyThread implements runnable{//implements Runnable interface public void Run () {//overwrite run () method System.out.println ("1, enter Run () method"); try {Thread.Sleep (10000);//thread sleeps 10 seconds System.out.println ("2, has completed hibernation");} catch (Interruptedexception e) {System.out.println ("3, Sleep is terminated"), return;//returns the}SYSTEM.OUT.PRINTLN at the call ("4, Run () method ends normally");}}; public class Threadinterruptdemo{public static void Main (String args[]) {MyThread MT = new MyThread ();//Instantiate runnable subclass Object th Read T = new Thread (MT, "thread");//Instantiate Thread object T.start ();//Start Thread Try{thread.sleep (2000);//thread sleeps 2 seconds}catch ( Interruptedexception e) {System.out.println ("3, Sleep is terminated");} T.interrupt ();//Interrupt Thread execution}};


Background Processin Java, as long as a program is not finished (a thread is running), the entire Java process will not disappear, so you can set a background thread at this point, so that even if the Java process is finished, then the next thread will continue to run, that is, does not affect the end of the process. To achieve this, use the Setdaemon () method directly.
Class MyThread implements RUNNABLE{//implementation Runnable interface public void Run () {//overwrite run () method while (true) {System.out.println ( Thread.CurrentThread (). GetName () + "is running. ") ;}}}; public class Threaddaemondemo{public static void Main (String args[]) {MyThread MT = new MyThread ();//Instantiate runnable subclass Object Threa D t = new Thread (MT, "thread");//Instantiate Thread object T.setdaemon (TRUE);//This thread runs T.start ();//Boot Thread}} in the background;
Will find that nothing is printed, and if set to false it will print all the time and will not end the process.priority of the threadIn a Java thread operation, all threads remain in a ready state before they run, so which thread has a high priority at this point and which thread is likely to be executed first.
Class MyThread implements RUNNABLE{//implementation Runnable interface public void Run () {//overwrite run () method for (int i=0;i<5;i++) {try{ Thread.Sleep (500);//thread hibernation}catch (interruptedexception e) {}system.out.println (Thread.CurrentThread (). GetName () + "run , i = "+ i);//Get the name of the current thread}}};p ublic class Threadprioritydemo{public static void Main (String args[]) {Thread T1 = new Thread (New MyThread (), "Thread A");//Instantiate thread object thread t2 = new Thread (new MyThread (), "thread B");//Instantiate thread object thread t3 = new Thread (new MYTHR EAD (), "Thread C");//Instantiate Thread Object T1.setpriority (thread.min_priority);//Lowest priority t2.setpriority (thread.max_priority);// Priority t3.setpriority (thread.norm_priority);//Priority Center T1.start ();//Start thread t2.start ();//Start thread t3.start ();//Start Thread}};


the priority of the main thread is norm_priority to 5 is the medium level. the default thread priority is also norm_priority. examples of the program are:
public class Mainprioritydemo{public static void Main (String args[]) {System.out.println ("Priority of the Main method:" + Thread.CurrentThread (). getpriority ());//Obtain the priority of the Main method System.out.println ("max_priority =" + thread.max_priority); System.out.println ("norm_priority =" + thread.norm_priority); System.out.println ("min_priority =" + thread.min_priority);};

Comity of Threadsin a thread operation, you can also use the yield () method to temporarily let another thread perform the operation.
Class MyThread implements RUNNABLE{//implementation Runnable interface public void Run () {//overwrite run () method for (int i=0;i<5;i++) {try{ Thread.Sleep (500);} catch (Exception e) {}system.out.println (Thread.CurrentThread (). GetName () + "run, I =" + i);//Gets the name of the current thread if (i==2) { System.out.print ("Thread comity:"); Thread.CurrentThread (). yield ();//Thread Comity}}}};p ublic class Threadyielddemo{public static void Main (String args[]) { MyThread my = new MyThread ();//Instantiate MyThread object thread t1 = new Thread (My, "thread A"); Thread t2 = new Thread (my, "thread B"); T1.start (); T2.start ();}};


Summary:The focus is on mastering the threading method, which only needs to be looked up from the thread class for these methods of operation. examples of threading operationsInstance requirements: Design a threading action class that requires the ability to produce three thread objects, and can set the sleep time of three threads, respectively, as follows:thread A, sleeps for 10 seconds. thread B, hibernate 20 secondsthread C, hibernate 30 seconds
Analysis: There are two ways to implement a known thread, one is to inherit the thread class, and the other is to implement the Runnable interface. And you should save the thread name and sleep time two properties in the class.
(i) using the thread classThe name attribute exists directly in the thread class.
Class MyThread extends Thread{private int time;p ublic MyThread (String name,int time) {super (name);//Set thread name This.time = Ti Me;//Set sleep time}public void Run () {try{thread.sleep (this.time);//Hibernate specified time}catch (interruptedexception e) { E.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + "thread, hibernate" + This.time + "milliseconds. ") ;}}; public class Execdemo01{public static void Main (String args[]) {MyThread MT1 = new MyThread ("Thread A", 10000);//Define Thread object, specify sleep time m Ythread mt2 = new MyThread ("Thread B", 20000);//Define Thread object, specify sleep time MyThread mt3 = new MyThread ("Thread C", 30000);//Define Thread object, specify sleep time Mt1.sta RT ();//Start thread mt2.start ();//Start thread mt3.start ();//Start Thread}};

(ii) Use of runnableIf you use the Runnable interface, there is no thread name in the class, so you should establish a Name property separately to hold the thread names.
Class MyThread implements Runnable{private string name;p rivate int time;p ublic MyThread (string name,int time) {THIS.name = name;//Set the thread name this.time = time;//Set the sleep time}public void Run () {try{thread.sleep (this.time);//Hibernate the specified period}catch (interruptede Xception e) {e.printstacktrace ();} System.out.println (THIS.name + "thread, hibernate" + This.time + "milliseconds. ") ;}}; public class Execdemo02{public static void Main (String args[]) {MyThread MT1 = new MyThread ("Thread A", 10000);//Define Thread object, specify sleep time m Ythread mt2 = new MyThread ("Thread B", 20000);//Define Thread object, specify sleep time MyThread mt3 = new MyThread ("Thread C", 30000);//Define Thread object, specify sleep time new THR EAD (MT1). Start ();//Start thread new Thread (MT2). Start ();//boot thread new Thread (MT3). Start ();//Start Thread}};


Common methods of operation for Java threads

Related Article

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.