An instance method in Java multithreaded 2:thread

Source: Internet
Author: User

Method invocation methods in the thread class:

Learning the methods in the thread class is the first step in learning multithreading. Before learning multithreading, in particular, when invoking the method in thread, there are two ways to understand the difference between the two ways in the thread class:

1, This.xxx ()

This invocation means that the thread is the thread instance itself

2, Thread.currentThread.XXX () or thread.xxx ()

The above two kinds of wording are the same meaning. This method of invocation represents the thread that is executing the code block where Thread.currentThread.XXX () resides

Of course, so to speak, someone must not understand the difference between the two. It doesn't matter, and then it's clear, especially if you're talking about the thread constructor. After the explanation, and then look back to the above 2 points, will deepen understanding.

Instance methods in the thread class

The method in thread is explained from the perspective of instance methods and class methods in the thread class, which also helps to understand the methods in multi-threading. The instance method, which is only tied to the instance thread (that is, the new thread) itself, is independent of which thread is currently running. Look at the instance method in the thread class:

1. Start ()

The function of the start () method is to tell the thread planner that this thread can run and is waiting for the CPU to call the thread object with the run () method, resulting in an asynchronous execution effect. By starting the start () method to get the conclusion, first look at the code:

public class MYTHREAD02 extends thread{public    void Run ()    {        try        {for            (int i = 0; i < 3; i++)            {                thread.sleep ((int) (Math.random () *));                System.out.println ("Run =" + Thread.CurrentThread (). GetName ());            }        }        catch (interruptedexception e)        {            e.printstacktrace ();}}    }
public static void Main (string[] args) {    MyThread02 mt = new MyThread02 ();    Mt.start ();           Try    {for        (int i = 0; i < 3; i++)        {            thread.sleep (int) (Math.random () *));            System.out.println ("Run =" + Thread.CurrentThread (). GetName ());        }    }    catch (interruptedexception e)    {        e.printstacktrace ();    }}

Look at the results of the operation:

Run = Thread-0run = Mainrun = Mainrun = Mainrun = Thread-0run = Thread-0

The result shows thatthe code for which thread the CPU executes is nondeterministic . Let's look at another example:

public class MyThread03 extends thread{public    void Run ()    {        System.out.println (Thread.CurrentThread (). GetName ());}    }
public static void Main (string[] args) {    MyThread03 mt0 = new MyThread03 ();    MYTHREAD03 MT1 = new MyThread03 ();    MYTHREAD03 mt2 = new MyThread03 ();            Mt0.start ();    Mt1.start ();    Mt2.start ();}

Look at the results of the operation:

thread-1thread-2thread-0

Although the boot thread follows Mt0, MT1, mt2, the actual boot order is Thread-1, Thread-2, and Thread-0. This example shows that the order in which the start () method is called does not represent the order in which the threads are started, and the thread boot order is nondeterministic .

2. Run ()

The thread starts executing and the virtual machine calls the contents of the thread run () method. Change the previous example slightly to see:

public static void Main (string[] args) {    MyThread02 mt = new MyThread02 ();    Mt.run ();            Try    {for        (int i = 0; i < 3; i++)        {            thread.sleep (int) (Math.random () *));            System.out.println ("Run =" + Thread.CurrentThread (). GetName ());        }    }    catch (interruptedexception e)    {        e.printstacktrace ();    }}

MYTHREAD02 code does not change, look at the results of the operation:

Run = Mainrun = Mainrun = Mainrun = Mainrun = Mainrun = Main

See "Run = Main" printed 6 times, stating that if only run () does not have a start (), the contents of the thread instance run () method have no asynchronous effect and are all executed by the main function. In other words, it does not make sense to start a thread with only run () without calling start ().

3, IsAlive ()

The test thread is active, as long as the thread starts and does not terminate, the method returns True. Take a look at the example:

public class MyThread06 extends thread{public    void Run ()    {        System.out.println ("Run =" + this.isalive ()); c4/>}}
public static void Main (string[] args) throws exception{    MyThread06 mt = new MyThread06 ();    SYSTEM.OUT.PRINTLN ("begin = =" + mt.isalive ());    Mt.start ();    Thread.Sleep (+);    System.out.println ("end = =" + mt.isalive ());}

Look at the results of the operation:

begin = = Falserun = TrueEnd = = False

It is true that the thread's IsAlive is False,start () before Start () is seen. The reason for adding thread.sleep (100) to the main function is to ensure that the code in the Thread06 's run () method is executed, otherwise it is possible for the end to print out true and be interested in experimenting with it yourself.

4, GetId ()

This method is relatively simple, do not write an example. In a Java application, there is a long, globally unique thread ID generator threadseqnumber, each new thread will increment this one, and give the thread the Tid property, which is done by the thread itself, the user cannot execute the ID of a thread.

5, GetName ()

This method is also relatively simple, and does not write an example. When we new a thread, we can specify the name of the thread, or we can not specify it. If specified, then the name of the thread is what we specify, and GetName () returns the name of the developer-specified thread, and if not specified, there is an int globally unique thread initializer Threadinitnum in thread. Java first threadinitnum, and then "Thread-threadinitnum" the way to name the newly generated thread

6, GetPriority () and setpriority (int newpriority)

These two methods are used to get and set the priority of the thread, the CPU resources of the higher priority CPUs are more, and the setting priority helps the thread planner determine which thread to select next time to take precedence. In other words, two threads waiting on the CPU, the more high priority threads are more likely to be executed by the CU selection . Let's take a look at the example and draw a few conclusions:

public class Mythread09_0 extends thread{public    void Run ()    {        System.out.println ("Mythread9_0 Run priority = "+                 this.getpriority ());}    }
public class Mythread09_1 extends thread{public    void Run ()    {        System.out.println ("Mythread9_1 Run priority = "+                 this.getpriority ());        Mythread09_0 thread = new Mythread09_0 ();        Thread.Start ();    }}
public static void Main (string[] args) {    System.out.println ("Main thread begin, Priority =" +             Thread.CurrentThread (). getpriority ());    System.out.println ("Main thread end, priority =" +             thread.currentthread (). getpriority ());    Mythread09_1 thread = new Mythread09_1 ();    Thread.Start ();}

Look at the results of the operation:

Main thread begin, priority = 5main thread end, priority = 5mythread9_1 Run priority = 5mythread9_0 Run priority = 5

From this example we conclude that the thread default priority is 5, and if you do not specify it manually, then the thread priority is inherited, such as thread A starts thread B, and thread B has the same priority as thread A. The following example shows the effect of setting the thread priority:

public class Mythread10_0 extends thread{public    void Run ()    {        Long beginTime = System.currenttimemillis (); c5/>for (int j = 0; J < 100000; J + +) {}        long endTime = System.currenttimemillis ();        SYSTEM.OUT.PRINTLN ("thread0 Use time =" +                 (Endtime-begintime));}    }
public class Mythread10_1 extends thread{public    void Run ()    {        Long beginTime = System.currenttimemillis ( );        for (int j = 0; J < 100000; J + +) {}        long endTime = System.currenttimemillis ();        SYSTEM.OUT.PRINTLN ("◇◇◇◇◇thread1 Use time =" +                 (Endtime-begintime));}    }
public static void Main (string[] args) {for    (int i = 0; i < 5; i++)    {        Mythread10_0 mt0 = new Mythread10_0 () ;        Mt0.setpriority (5);        Mt0.start ();        Mythread10_1 MT1 = new Mythread10_1 ();        Mt1.setpriority (4);        Mt1.start ();    }}

Look at the results of the operation:

thread0 Use time = 0 thread0 with time = 0 thread0 Use time = 1 thread0 with time = 2 thread0 use Time = 2◇◇◇◇◇thread1 Use time = 0◇◇◇◇◇thread1 use time = 1◇◇◇◇◇thread1 with time = 5◇◇◇◇◇thread1 use time = 2◇◇◇◇◇thre Ad1 Use time = 0

See the Black Diamond (thread priority high) print out first, and then try a few more times is the same. To create a contrast, set the priority of the YMYTHREAD10_0 to 4 and look at the results of the operation:

thread0 Use time = 0◇◇◇◇◇thread1 with time = 1◇◇◇◇◇thread1 use time = 1 thread0 Use time = 0◇◇◇◇◇thread1 use Time = 0 thread0 Use time = 1 thread0 Use time = 1◇◇◇◇◇thread1 with time = 2◇◇◇◇◇thread1 use time = 1 thre ad0 Use time = 0

See, the difference is coming out. From this example we conclude that theCPU will try to give execution resources to the higher priority threads .

7, Isdaemon, Setdaemon (Boolean on)

Before explaining the two methods, you should first understand the concept of understanding. There are two kinds of threads in Java, one is a user thread and one is a daemon thread. A daemon thread is a special thread that serves as a convenient service for the operation of other threads, and the most typical application is GC threads. If there is no non-daemon thread in the process, then the daemon thread is automatically destroyed, because there is no need to serve others, the result of the service objects are gone, of course, destroyed. After understanding the concept, take a look at the example:

public class MyThread11 extends thread{    private int i = 0;        public void Run ()    {        try        {            while (true)            {                i++;                System.out.println ("i =" + i);                Thread.Sleep (+);            }        }         catch (interruptedexception e)        {            e.printstacktrace ();}}    }
public static void Main (string[] args)    {        try        {            MyThread11 mt = new MyThread11 ();            Mt.setdaemon (true);            Mt.start ();            Thread.Sleep (the);            System.out.println ("I left the thread object no longer printing, I stopped!") ");        }        catch (interruptedexception e)        {            e.printstacktrace ();        }    }

Look at the results of the operation:

1 i = 1 2 i = 2 3 i = 3 4 i = 4 5 i = 5 6 I left the thread object to print again, I stopped! 7 I = 6

To explain. We set the MYTHREAD11 thread to the daemon thread and saw the 6th line, and I stopped at 6 and no longer ran. This means that the main thread runs for more than 5 seconds, and I accumulate once every 1 seconds, 5 seconds after the main thread finishes executing, MyThread11 as the daemon thread, the main function is run out, naturally there is no need to exist, it is automatically destroyed, so there is no further down printing numbers.

With regard to the daemon thread, there is a detail to note that Setdaemon (true) must be before the thread start ()

8, interrupt ()

This is a somewhat misleading name, in fact the interrupt () method of the thread class does not break thread. Take a look at the example:

public class testmain12_0{public    static void Main (string[] args)    {        try        {            MyThread12 mt = new MyThread12 ();            Mt.start ();            Thread.Sleep (+);            Mt.interrupt ();        }         catch (interruptedexception e)        {            e.printstacktrace ();}}    }
public void Run () {for    (int i = 0; i < 500000; i++)    {        System.out.println ("i =" + (i + 1));}    }

Look at the results of the operation:

...
i = 499995i = 499996i = 499997i = 499998i = 499999i = 500000

The results were printed at 50000. That is, although the interrupt () method is called, the thread does not stop. The interrupt () method actually works by throwing an interrupt signal when the thread is blocked, so that the threads can exit the blocking state . In other words, without a blocked thread, calling the interrupt () method is not working. About this will be in the later talk about the interruption mechanism, write a special article to explain.

9, isinterrupted ()

Tests whether the thread has been interrupted, but does not clear the status identity. This, like the interrupt () method, is specifically addressed in the article on the interrupt mechanism that follows.

10. Join ()

Before you explain the join () method, make sure that you are familiar with the http://www.cnblogs.com/xrq730/p/4853932.html, the Wait ()/notify ()/notifyall () mechanism.

The join () method works by waiting for the thread to be destroyed. The join () method responds to a very real problem, such as the execution time of the main thread is 1s, the execution time of the sub-thread is 10s, but the main thread relies on the results of the child thread execution, what should I do? Can be like a producer/consumer model, a buffer, sub-thread execution of the data in the buffer, notify the main thread, the main thread to fetch, so that the main thread will not waste time. Another way is to join (). Let's take a look at the example:

public class MyThread36 extends thread{public    void Run ()    {        try        {            int secondvalue = (int) ( Math.random () * 10000);            System.out.println (secondvalue);            Thread.Sleep (secondvalue);        }         catch (interruptedexception e)        {            e.printstacktrace ();}}    }
public static void Main (string[] args) throws exception{    MyThread36 mt = new MyThread36 ();    Mt.start ();    Mt.join ();    SYSTEM.OUT.PRINTLN ("I want to do it again after the Mt object has been executed, I did");}

Look at the results of the operation:

3111 I want to do it when the Mt object is finished, I did it.

This means that the join () method will cause the thread (that is, the MT thread) that is calling the join () method to block indefinitely until the thread that calls the join () method is destroyed, and in this case the main thread will block indefinitely until the Mt's run () method finishes executing.

A key point of the Join () method is to differentiate between the sleep () methods. Join (2000) is also possible, indicating that the thread that calls the join () method waits at most 2000ms, and the difference is:

Sleep (2000) does not release the lock, and join (2000) releases the lock because the join () method internally uses wait () and therefore releases the lock. Take a look at the source of join (2000) and know that join () is actually the same as join (2000), nothing more than join (0):

1 public final synchronized void join (Long Millis)  2     throws interruptedexception {3     long base = System.curren Ttimemillis (); 4     Long now = 0, 5  6     if (Millis < 0) {7             throw new IllegalArgumentException ("Timeout value is negative") ; 8     } 9     if (Millis = = 0) {One         while (IsAlive ()) {Ten         wait (0);         }14     } else {all         (isAl Ive ()) {         long delay = millis-now;17         if (delay <= 0) {             break;19         }20         Wait (delay); 21 Now         = System.currenttimemillis ()-Base;22         }     }24     }

Lines 12th and 20th should already be clear.

An instance method in Java multithreaded 2: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: 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.