The most complete multi-threading learning summary 1-- java-thread basis

  "Java core technology" This book is really good, very comprehensive knowledge points, translation quality is also good, this series Bowen is a summary of the book's chapters concurrently.

What is the thread

  The official explanation: the thread is the smallest unit of an operating system capable of scheduling operations, including in the process of being, is the actual operation of the unit process. That thread is the carrier code running, our code is run on a thread to one of the most simple hellowWorld example:

public class Main {

    public static void main(String[] args) {
        System.out.println("Hello World!");
        System.out.println("当前线程名为:"+Thread.currentThread().getName());
        System.out.println("当前线程id为:"+Thread.currentThread().getId());
    }
}

The results are:

Hello World!
当前线程名为:main
当前线程id为:1

The default creates a main thread to execute the code, the program runs a thread titled: main, thread id 1

What is multi-threaded

  As the name suggests is that multiple threads to run simultaneously, improve program execution speed. Single thread can only do one thing, you want to improve the efficiency of two ways:

  • asynchronous. Because most of the time the thread is not the time in calculations, are awaiting io action, the wait time can be utilized to improve the utilization of the thread. Do not make too much discussion and want to learn more about asynchronous learn Node.js (native support asynchronous)
  • Multithreading. A thread can only do one thing, then multiple threads will be able to do more things simultaneously, to increase execution speed by increasing the number of threads.

How to create a thread

  There are two ways to create a thread

  • Thread class inheritance
  • Implement runnable interfaces

Thread class inheritance

  This is not recommended way to create a thread, for obvious reasons: java does not support multiple inheritance, if you can not inherit the Thread class inherits the other class.

  Creating threaded code inheritance is used as follows:

public class CustomThreadExtendThread extends Thread{

    @Override
    public void run() {
        String threadName = Thread.currentThread().getName();
        long threadId = Thread.currentThread().getId();
        System.out.println("创建线程名为:"+threadName+",id为:"+threadId);
    }

    public static void main(String[] args){
        Thread thread1 = new CustomThreadExtendThread();
        Thread thread2 = new CustomThreadExtendThread();
        thread1.start();
        thread2.start();
    }
}

Implement runnable interfaces

  Implement the interface to create a thread is currently recommended as a way, the reason is simple: a class can implement multiple interfaces. Implement Runnable interface does not affect the implementation class to go to implement other interfaces.

  Use the following code to create a thread to achieve Interface:

public class CustomThreadImplementInterface implements Runnable {
    @Override
    public void run() {
        Thread.currentThread().setName(((Double) Math.random()).toString());
        String threadName = Thread.currentThread().getName();
        long threadId = Thread.currentThread().getId();
        System.out.println("创建线程名为:" + threadName + ",id为:" + threadId);
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(new CustomThreadImplementInterface());
        Thread thread2 = new Thread(new CustomThreadExtendThread());
        thread1.start();
        thread2.start();

        //使用lambda表达式,让创建线程更简单
        new Thread(() -> {
            System.out.println("创建了一个新线程");
        }).start();
    }
}

  You can see the Thread class is a class that implements the Runnable interface Thread by looking at the source code.

PS: Follow all use the code to create runnable threads

Thread State

  The above are just demonstrates thread creation, and now to learn more about the state of the thread. In java specification, the thread can have the following six states:

  • New (newly created)
  • Runnable (run)
  • Blocked (blocking)
  • Waiting (waiting)
  • Timed waiting (waiting timer)
  • Terminated (terminated)

The newly created thread

  When a thread is created using the new operator, as new Thread (r), the threads have not running, belongs to the newly created state.

Runnable threads

  Once the Thread class start method call, the thread is runnable state.

Why call can run the state?

  Because Java specification and will not run on the CPU being defined as a separate state. So are runnable threads may be running or may not run, depending on the CPU scheduling policy.

And the thread is blocked waiting threads

  When the thread is blocked or wait state, does not run any code and consuming minimal resources. Until the re-run. There are several ways of getting blocked or thread into the wait state:

  • When a thread attempts to acquire an internal object lock, and the lock is held by another thread
  • When the thread is waiting for another thread scheduler notifies a condition enters a wait state. For example, call Object.wait or Thread.join methods, or wait for the library java.util.concurrent Lock Condition or when.
  • When the call timing wait method. For example Thread.sleep, Object.wait, Thread.join, Lock.tryLock and Condition.await

Terminated thread

  Thread by the following two ways to enter the final state:

  • The end of the run method and natural death
  • Uncaught abort the run method and accidental death

Note: STOP method calling thread can also terminate the thread, but this method has been abandoned, it is best not to use.

Thread Attributes

  Thread has various attributes: Priority, daemon thread, and the thread group uncaught exception handling processor.

Thread priority

  java, each thread has a priority. By default, thread inherits parent thread priority. You can also call setPrioritythe method specified priority. Priority Range: 1 (MIN_PRIORITY) -10 (MAX_PRIORITY ) .NORM_PRIORITY 5, these constants are defined in the Thread class.

Note: highly dependent on the thread priority system, so that when priority java thread priorities are mapped to the host platform, the number of priorities may become less or become 0. For example, Windows has seven prioritized when java thread mapping section priority will be mapped to the same operating system priority. Oracle Linux is written in java virtual machine, ignoring the thread priority, all java threads have the same priority. Do not write code that relies priority .

Daemon thread

  By calling Thread.setDaemon(true)the thread is converted to a daemon thread. The only user daemon thread is to provide services to other threads, such as thread timing, the timing of the timing signal is sent to the other thread. Therefore, when the virtual machine is only daemon threads, virtual machine shuts down exit. Do not access any resources in the thread guard, handle any business logic

Uncaught exception handler

  Thread run method can not throw any checked exception, non checked exception causes the thread to terminate, in addition to try / catch catch the exception, but also by the uncaught exception processor to handle the exception. The exception handler need to implement the Thread.UncaughtExceptionHandlerinterface.

  An example of a thread can use setUncaughtExceptionHandler()the method setting processor for a thread, it may also be used Thread.setDefaultUncaughtExceptionHandler()for all processor threads default settings, as follows:

public class CustomExceptionHandler implements Thread.UncaughtExceptionHandler {

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.out.println("捕获到线程"+t.getName()+",异常:" + e.getMessage());
        e.printStackTrace();
    }

    public static void main(String[] args) {
        Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler());
        new Thread(() -> {
            throw new RuntimeException("test");
        }).start();
    }
}

  Thread group object If you do not set the default processor and not as a separate processor threads settings, then the thread of the processor for the thread of --ThreadGroup (because the thread group object implements Thread.UncaughtExceptionHandlerthe interface).

Benpian all the code used: GitHub

Benpian Original Posted: https://www.tapme.top/blog/detail/2019-04-08-20-52

Guess you like

Origin www.cnblogs.com/wuyoucao/p/11100889.html