"Java Concurrency series 01" Thread and Threadgroup

Source: Internet
Author: User
Tags stack trace terminates throwable

First, preface

Recently began to learn Java concurrent programming, the learning process recorded. Estimation is not so system, mainly should be the introduction of Java API (not related to the most basic concept introduction), want to go into the system study recommended to read a book "Java Concurrency in practice" (suggested to see English, also can read Chinese translation: "Java concurrent Programming Combat").

The basis of concurrent programming is threading, so this article makes a preliminary understanding of threading.

Ii. the relationship between thread and Thredgroup

Because there are thradgroup in the constructor of thread, it is necessary to understand the relationship between them. The relationship between Thradgroup is a tree, and the relationship between thread and Thradgroup is like the relationship between elements and sets. The diagram is simple as follows:

One thing to be clear about is that the root thread group does not need to be created, and the main method automatically creates the root thread group and places the main thread in it

Third, Thread API

3.1 Basic Properties

You should first understand the basic properties of a thread:

    • Name: thread names, which can be duplicated, are automatically generated if not specified.
    • ID: Thread ID, a positive Long value, specified when the thread was created, lifetime unchanged, the ID can be reused when the thread is terminated.
    • Priority: Thread priorities, the value is 1 to 10, the higher the thread priority, the greater the likelihood of execution, if the running environment does not support priority level 10, such as only support 5 levels, then set 5 and set 6 may be the same.
    • State: Thread Status, Thread.state enumeration type, there are 5 kinds of new, RUNNABLE, BLOCKED, waiting, timed_waiting, TERMINATED.
    • Threadgroup: The owning thread group, a thread must have the owning thread group .
    • Uncaughtexceptionhandler: The processor that did not catch the exception, by default, terminates the current thread immediately after a thread error and prints an error.
3.2 Field Summary

The thread class has three fields, which you can use when you set the priority of threads:

    • Min_priority:1, lowest priority
    • Norm_priority:5, Normal priority
    • Max_priority:10, highest priority
3.3 Construction methods

Now only one of the parameters is described:

Thread (threadgroup group, Runnable Target, String name, long stackSize)

    • Group: Specifies the thread group for the current thread, not specified when the thread group is creating the thread group to which the thread belongs.
    • Target: Specifies that the runnable is to be run, that the specified thread is not meaningful, or you can rerun the Run method by creating a subclass of the thread.
    • Name: The names of the threads, not specified for automatic generation.
    • StackSize: Expected stack size, no default is 0, 0 means ignore this property. This property is not recommended for platform-related use.
3.4 Method Summary 3.4.1 static method
    • thread Thread.CurrentThread () : Gets a reference to the current thread. Manipulate the current thread after it has been acquired.
    • Thread.uncaughtexceptionhandler Getdefaultuncaughtexceptionhandler (): Returns the default handler that is called when the thread terminates abruptly because the exception was not caught.
    • int Thread.activecount (): The number of active threads in the thread group that is currently threads.
    • void DumpStack (): Prints the stack trace of the current thread to the standard error stream.
    • int enumerate (thread[] tarray): Copies each active thread in the current thread's thread group and its subgroups into the specified array.
    • Map<thread,stacktraceelement[]> getallstacktraces (): Returns a map of the stack traces for all active threads.
    • Boolean holdslock (Object obj): Returns True if and only if the monitor lock is persisted on the specified object by the front thread.
    • Boolean interrupted (): Tests if the front thread has been interrupted.
    • void Setdefaultuncaughtexceptionhandler (Thread.uncaughtexceptionhandler eh): Sets when a thread terminates abruptly because an exception was not caught. And there is no default handler that is called when other handlers are defined for the thread.
    • void sleep (Long Millis): Hibernate specified time
    • void sleep (long millis, int nanos): Hibernate specified time
    • void yield (): Pauses the currently executing thread object and executes other threads. It doesn't mean much.
3.4.2 Common method
  • void CheckAccess (): Determines whether the currently running thread is authorized to modify the thread.
  • ClassLoader Getcontextclassloader (): Returns the thread's context ClassLoader.
  • Long GetId (): Returns the identifier of the thread.
  • String getName (): Returns the name of the thread.
  • int getpriority (): Returns the priority of the thread.
  • Stacktraceelement[] Getstacktrace (): Returns an array of stack trace elements representing the stack dump of the thread.
  • Thread.state getState (): Returns the state of the thread.
  • Threadgroup Getthreadgroup (): Returns the thread group to which the thread belongs.
  • Thread.uncaughtexceptionhandler Getuncaughtexceptionhandler (): Returns the handler that is called when the thread terminates abruptly because the exception was not caught.
  • void interrupt (): Middle break thread.
  • Boolean isAlive (): Tests whether the thread is active.
  • Boolean Isdaemon (): Tests whether the thread is a daemon thread.
  • Boolean isinterrupted (): The test thread has been interrupted.
  • void join (): Waits for the thread to terminate.
  • void join (Long Millis): The maximum time to wait for the thread to terminate is Millis milliseconds.
  • void Join (long millis, int nanos): waits for the thread to terminate for a maximum of Millis milliseconds + Nanos nanoseconds.
  • void Run (): The method that is executed after the thread starts.
  • void Setcontextclassloader (ClassLoader cl): Sets the context ClassLoader for the thread.
  • void Setdaemon (Boolean on): marks the thread as either a daemon thread or a user thread.
  • void Start (): Causes the thread to start executing, and the Java virtual machine calls the thread's Run method.
  • String toString (): Returns the string representation of the thread, including the thread name, priority, and thread group.
3.4.3 void method
    • int Countstackframes (): No meaning, no explanation.
    • void Destroy ():
    • void Resume ():
    • void Stop ():
    • void Stop (Throwable obj):
    • void Suspend ():
3.5 Thread Knowledge Method explained 3.5.1 Setdefaultuncaughtexceptionhandler (Thread.uncaughtexceptionhandler eh)

The first thing to know is Thread.uncaughtexceptionhandler, by default, when a thread catches an uncaught exception, it breaks and throws an exception, and the thrown action has only a simple stack output. Such as:

 Public class threadtest{    publicstaticvoidthrows  exception{        Thread T1 =new Thread (new  Runnable () {            publicvoid  Run ( {                int a=1/0;            }        });        T1.start ();    }}

Then the code runs to int a=1/0; it will error:

Exception in Thread "Thread-0" java.lang.ArithmeticException:/by zero at    Yiwangzhibujian. threadtest$1.run (threadtest.java:11) at    java.lang.Thread.run (Thread.java:662)

At this point, if Thread.uncaughtexceptionhandler is set, the processor captures the exception and can be processed after it is captured:

 Public classthreadtest{ Public Static voidMain (string[] args)throwsexception{Thread T1=NewThread (NewRunnable () { Public voidrun () {inta=1/0;        }        }); T1.setuncaughtexceptionhandler (NewUncaughtexceptionhandler () {@Override Public voiduncaughtexception (Thread t,throwable e) {System.out.println ("Thread:" +t.getname () + "Exception occurred, exception information:" +e);        }        });    T1.start (); }}

Then when the thread throws an exception, it can be crawled and processed, and the end result is as follows:

Thread: Thread-0 exception, exception information: java.lang.ArithmeticException:/by zero

If you write the thread yourself, you can do the same in the catch by doing all the code in the Run method. The point of Uncaughtexceptionhandler is to add an error handler to an existing thread without modifying it (or not).

3.5.2 interrupt (), Interrupted (), isinterrupted () effect

Since the stop () method is no longer recommended, how to break a thread becomes a problem, and an easy way is to set a global variable needstop, as follows:

@Override  Public void run () {    while (!  Needstop) {        // perform certain tasks     }}

Or it takes a long time for the operation to be judged before each step is executed:

@Override  Public void run () {    //Take longer step 1    ifreturn;     // Takes a long time to step 2    if return ;     // Takes a long time to step 3}

This will stop the thread in other places, because the stop is in its own anticipation, so there will be no deadlock or data anomalies (of course, you should be careful when writing your program).

In fact, the thread class has long had a similar function, that is, thread has the interrupt attribute. You can set the thread break property to True by calling the interrupt () method, which results in the following two scenarios:

    • When a thread is running correctly, the interrupt property is set to true, and calling its isinterrupted () method returns True.
    • When the thread is blocked (the Wait,join,sleep method), the interruptedexception exception is thrown immediately and the break property is set to False. Calling isinterrupted () again now returns false.

This is done by the program to determine how the thread interrupts are handled. Therefore, the above code can be changed to:

@Override Public voidrun () { while(!Thread.CurrentThread (). isinterrupted ()) {        //perform certain tasks    }}---------------------------------------------------------@Override Public voidrun () {//Takes a long time to step 1    if(Thread.CurrentThread (). isinterrupted ())return; //Takes a long time to step 2    if(Thread.CurrentThread (). isinterrupted ())return; //Takes a long time to step 3}

The method name of interrupted () is easy to give people a misunderstanding, its true meaning is

3.5.3 yield () and sleep (0)

The yield () method API is misleading, and its actual meaning is to stop executing the current thread (immediately) and let the CPU re-select the thread that needs to be executed because it is random, so it is possible to re-execute the thread, as shown in the following example:

 Public classthreadtest{ Public Static voidMain (string[] args)throwsexception{Thread T1=NewThread (NewRunnable () {@Override Public voidrun () { while(true) {System.out.println (1);                Thread.yield ();        }            }        }); Thread T2=NewThread (NewRunnable () { Public voidrun () { while(true) {System.out.println (2);                Thread.yield ();        }            }        });        T1.start ();    T2.start (); }}

The result of the program execution is not 121212 but there is a continuous 1 and a continuous 2.

After testing yield () and sleep (0) The effect is the same, sleep (0) The bottom layer is either with yield () is either filtered out (purely by guessing), but sleep (0) does not make any sense. If you really want to suspend the current thread or you should use sleep (long millis,int Nanos) This method, set a few nanoseconds for sincerity, or find the thread that you want to compromise, the join method that calls it is more practical.

3.5.4 Stop (), suspend (), resume () Why not recommend using

The Stop method immediately disconnects the thread, although it releases the lock that is held, but where it is unknown, if it is interrupted in a context-sensitive location, it will cause an error in the information, such as:

@Override  Public void run () {    try{        // process resource and insert database    }catch( Exception e) {        //  unexpected rollback     }}

If the code runs to the point where the catch exception needs to be rolled back when the stop is called, an error message will be produced.

Suspend will suspend the current thread, but it will not release the resources it holds, and if the recovery thread needs that resource to call resume, a deadlock will be formed. Of course, you can avoid deadlocks through your superb programming, but this approach has inherent deadlock tendencies. Therefore, it is not recommended. Why other pause methods are available:

    • The Wait method releases the lock, so there is no deadlock problem
    • Although the Sleep method does not release the lock, it does not need to wake up and specifies the desired sleep time when it is used.
Iv. threadgroup API

4.1 Basic Properties

Name: The names of the current threads.

Parent: The group of parents for the current thread group.

Maxpriority: The highest priority of the current thread group, where the thread priority cannot be higher.

4.2 Construction Methods

Only one construction method is described:

Threadgroup (threadgroup parent, String name):

    • Parent: The group of parents, if specified, is the thread group that is required for the thread that created the thread group.
    • Name: The names of thread groups, which can be duplicated.
4.3 Summary of common methods

API detailed (Chinese, English).

    • int Activecount (): Returns the estimated number of active threads in this thread group.
    • void Interrupt (): Interrupts all threads in this thread group.
    • void Uncaughtexception (Thread T, throwable e): Sets the exception handler for the current thread group (only valid for threads that do not have an exception handler).
4.4 Threadgroup Effect

This thread group can be used to manage a set of threads and to see the number of active threads through Activecount ().  

This blog explains the most basic threads and thread groups, which is the foundation of concurrent programming and should be fully understood.

No reprint without permission.

"Java Concurrency series 01" Thread and Threadgroup

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.