Concurrent programming of thread attributes

  The main thread of various attributes discussed herein, comprising: a main thread, thread priority, daemon thread, a thread group, the uncaught exception handling processor.

 
The main thread
 
  When any Java program starts, will start at least one thread executes the main method, this thread is called the main thread (main thread). It is to produce a thread other thread, namely: the main thread of the other threads all descendants thread. In general, the main thread is the last end, because it is closed to perform the work of other sub-threads.
 
Thread priority
 
  The computer has only one CPU, each thread in turn acquired the right to use the CPU to perform the task. In order to determine which priority thread execution, each thread to set a priority, a high priority thread priority will be executed. By default, the priority of each thread inherits its parent thread (the thread create thread) priority. The priority is an integer between 1 and 10, under normal circumstances, the thread default priority is 5. There are three common priority (1: MIN_PRIORITY, 5: NORM_PRIORITY, 10: MAX_PRIORITY).
public class Priority {


    @Test
    public void defaultPriority(){
        int mainThreadPriority = Thread.currentThread().getPriority();
        System.out.println("default priority is "+mainThreadPriority);//5
    }


    @Test
    public void extendFather(){
        Thread mainThread = Thread.currentThread();
        mainThread.setPriority(4);
        int mainThreadPriority = mainThread.getPriority();
        System.out.println("main thread's priority is "+mainThreadPriority);//4
        Thread t1 = new Thread(() -> System.out.println(Thread.currentThread().getName()),"t1");
        System.out.println("t1 thread's priority is "+t1.getPriority());//4
    }
}

Related API:

void setPriority ( int priority) Set thread priority
 int getPriority () Gets thread priority

 

Daemon thread

    The only role of the guardian of the thread is to provide services for the other threads, never to visit the natural resources in the daemon threads, such as files, databases and so on. When all user threads are finished, a daemon thread will end. And when only daemon threads, virtual machine exits.
 
     By default, the thread created by the user thread is still user thread, the thread created by the daemon threads still daemon thread.
 
    Garbage collection thread Java virtual machine is a typical daemon threads.
 
    Related API:
void setDaemon ( Boolean isDaemon) is provided as a daemon thread or threads user thread. This method must be called before the thread is started.
boolean isDaemon () to determine if this thread is a background thread

 

Thread Group

    Thread group is a collection of thread can be unified management, thread group may also include other thread groups. By default, all threads belonging to the same thread group. The thread can only access information where their thread group, other threads can not access information group, including the parent thread group is the thread group.
 
    Do not recommend using thread group (has better features for operating set of threads)
public class ThreadGroupDemo {

    public static void print(){
        Thread thread = Thread.currentThread();
        System.out.println(thread.getThreadGroup().getName()+"-"+thread.getName());
    }
    
    public static void main(String[] args) {
        ThreadGroup group = new ThreadGroup("Print Group");
        new Thread(group, ThreadGroupDemo::print, "t1").start();
        new Thread(group, ThreadGroupDemo::print, "t2").start();
        group.list();

    }
}

 

Uncaught exception handler

  Thread run () can not throw any abnormality is detected [as defined in the interface Runnable run () does not throw an exception, so rewriting the run (), not allowed to throw an exception, you can catch the exception using a try-catch] . However, if not detected abnormality does not use try-catch processing, causes the thread to death when an exception occurs. (Such as the example below, the console does not output "Endind?")

public class UncaughtExceptionDemo implements Runnable{

    @Override
    public void run() {
        int i = 1/0;
        System.out.println("Endind?");
    }


    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(1);
        service.execute(new UncaughtExceptionDemo());
    }
}

/* log:
...
Exception in thread "pool-1-thread-1" java.lang.ArithmeticException: / by zero
    at concurrency.attributes.UncaughtExceptionDemo.run(UncaughtExceptionDemo.java:10)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
*/

  Moreover, in the run manually throws an exception, using a try-catch in the main processing in a runtime exception, it did not take effect. (The following example, the console does not output "Current thread occurs exception.")

public class UncaughtExceptionDemo implements Runnable{

    @Override
    public void run() {
        int i = 1/0;
    }


    public static void main(String[] args) {
        try{
            ExecutorService service = Executors.newFixedThreadPool(1);
            service.execute(new UncaughtExceptionDemo());
        } catch (RuntimeException e){
            System.out.println("Current thread occurs exception.");
        }
    }
}

/*
...
Exception in thread "pool-1-thread-1" java.lang.ArithmeticException: / by zero
    at concurrency.attributes.UncaughtExceptionDemo.run(UncaughtExceptionDemo.java:10)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
*/

   So, how should handle thread exceptions thrown it? In fact, after the exception occurs before the thread dies, the exception will be passed to a processor for uncaught exceptions. You can use the processor to process threads thrown.

Import java.util.concurrent.ExecutorService;
 Import java.util.concurrent.Executors; 


public  class ThreadExceptionResolve the implements the Runnable { 


    @Override 
    public  void RUN () {
         int I = 1/0 ; 
        (System.out.println "? Endind" ) ; 
    } 


    public  static  void main (String [] args) {
         // 2. settings for all threads "exception handler" 
        Thread.setDefaultUncaughtExceptionHandler ( new new MyUncaughtExceptionHandler ());
         // 3. Create a thread of execution, and
        = Executors.newFixedThreadPool-Service ExecutorService (. 1 ); 
        service.execute ( new new ThreadExceptionResolve ()); 
    } 
} 


// 1. meet defined specification exception handler thread "exception handler"
 // The processor must belong to one implementation Thread. UncaughtExceptionHandler class interface 
class MyUncaughtExceptionHandler the implements the Thread.UncaughtExceptionHandler { 


    @Override 
    public  void the uncaughtException (the Thread T, the Throwable E) { 
        System.out.println ( "iS of the acculation error." ); 
    } 
} 

/ * 
... 
of the iS error acculation . 
* /

  A processor installed in two ways: use Thread static methods setDefaultUncaughtExceptionHandler (UncaughtExceptionHandler eh) the default settings for all processor threads, Thread may be used in the method of Example setUncaughtExceptionHandler (UncaughtExceptionHandler eh) is set to touch a thread processor. If the thread is not installed processor, the processor is at this time ThreadGroup object in return.

// for all processor threads default settings 
Thread.setDefaultUncaughtExceptionHandler (Handler); 


// the specified thread processor provided 
the Thread mainThread = Thread.currentThread (); 
mainThread.setUncaughtExceptionHandler (Handler);

 

  

Guess you like

Origin www.cnblogs.com/BlueStarWei/p/11622421.html