Java multi-thread basis (a)

Brief introduction

In the contacting 多线程before in our program can only perform one step at any time, call 单线程. All procedures are performed sequentially in the path of the single-threaded program developed in front of you must perform, the latter will be performed. The advantages of single-threaded also evident, more stable relative to the multi-threaded, the more scalable, application development is relatively easy. However, because each will have to wait a mandate to start a new task is completed, resulting in lower efficiency than the multi-threaded, and even sometimes the application will appear the phenomenon of suspended animation. The use of multi-threading in favor of fully functional multi-processor. By creating multithreaded process, each thread running on a processor, enabling concurrent applications, so that each processor are fully operational. Multithreading is a very important aspect of learning Java, Java is that each programmer must master basic skills. This article is about some basic knowledge of Java multi-threaded summarized.

The difference between processes and threads

process

Process is the 操作系统资源分配basic unit, it is the underlying operating system, is the activity that occurs when a program and data execution order on the processor. A program into the memory to run, that becomes a process. Process is in the process of running the program, and with a certain separate functions. In essence, the process of program execution in the operating system of a process that is dynamically generated, dynamic destruction, has its own life cycle and a variety of different operating states. Meanwhile, the process also has concurrency, it can be executed concurrently together with other processes, according to the independent, unpredictable speed forward ( PS:并发性和并行性是不同的概念,并行指的是同一时刻,两个及两个以上的指令在多个处理器上同时执行。而并发指的是同一时刻只有一条指令执行,但是多个进程可以被 CPU 快速交换执行,给我们感觉好像是多个执行在同时执行一样). 

Thread

A thread is 任务调度和执行a basic unit, also referred to as 轻量级进程thread by the thread ID, the current instruction pointer (PC), register set and stack components. Thread does not own the system resources, it will only have a little essential resources at run time, but it can share all the resources owned by the process and thread belong to the same process. A thread can only belong to one process, and a process can have multiple threads, but there is at least one thread.

The difference between the two
  1. Scheduling thread scheduling and assignment as the basic unit processes as the basic unit of own resources
  2. Concurrency between processes not only can execute concurrently, it can be executed concurrently across multiple threads of the same process
  3. Have the resources process is an independent unit with the resources, the thread does not have the system resources, but is part of the process of access to resources
  4. Overhead when creating or revocation process, because the system must be recomputed and resource recovery, leading to system overhead is significantly greater than the cost of creating or revoke thread

Create a thread way

In the Java Thread class represents a thread, all the thread object must be an instance of the Thread class or a subclass of, Java threads are created mainly in the following three ways:

A way to inherit the Thread class

step 1 define a class that inherits from Threadclass, and then override the class runmethod, this method represents a thread to complete the task

step 2 to create a thread object is created Threadinstance of a subclass of class

step 3 is created out of two steps object call startmethod to start a thread

/**
 * @author mghio
 * @date: 2019-12-07
 * @version: 1.0
 * @description: 通过继承 Thread 类的方式创建线程
 * @since JDK 1.8
 */
public class CreateThreadByExtendsThread extends Thread {

  @Override
  public void run() {
    IntStream.rangeClosed(1, 10).forEach(i -> System.out.println(Thread.currentThread().getName() + " " + i));
  }

  public static void main(String[] args) {
    CreateThreadByExtendsThread threadOne = new CreateThreadByExtendsThread();
    CreateThreadByExtendsThread threadTwo = new CreateThreadByExtendsThread();
    CreateThreadByExtendsThread threadThree = new CreateThreadByExtendsThread();

    threadOne.start();
    threadTwo.start();
    threadThree.start();
  }

}
复制代码
Second way to achieve Runnable interface

step 1 define a class that implements the Runnableinterface, and then implement the interface runmethod, this method also means the thread to complete the task

step 2 to create Runnableinstances of the class interface, and use that as an example of Thraedconstructor parameter to create Threadan object class, the object is the real thread object

step 3 calling thread object startmethod to start the thread

/**
 * @author mghio
 * @date: 2019-12-07
 * @version: 1.0
 * @description: 通过实现 Runnable 接口的方式创建线程
 * @since JDK 1.8
 */
public class CreateThreadByImplementsRunnable implements Runnable {

  @Override
  public void run() {
    IntStream.rangeClosed(1, 10).forEach(i -> System.out.println(Thread.currentThread().getName() + " " + i));
  }

  public static void main(String[] args) {
    CreateThreadByImplementsRunnable target = new CreateThreadByImplementsRunnable();
    new Thread(target, "thread-one").start();
    new Thread(target, "thread-two").start();
    new Thread(target, "thread-three").start();
  }

}
复制代码
Three ways to achieve Callable Interface

step 1 define a class that implements the Callableinterface, and then implement the interface callmethod, this method also indicates the thread to complete the task, and returns a value

step 2 Create Callableinstance of the class interface, using the FutureTaskclass to wrap Callablethe object, the FutureTaskobject encapsulates the Callableobject's callreturn value of the method

step 3 and use the FutureTaskobject as a Thraedcreation argument constructor of Threadthe object, and call the object's startmethod to start a thread

step 4 call the FutureTaskobject's getmethod to get the return value after the end of the thread execution

/**
 * @author mghio
 * @date: 2019-12-07
 * @version: 1.0
 * @description: 通过实现 Callable 接口的方式创建线程
 * @since JDK 1.8
 */
public class CreateThreadByImplementsCallable implements Callable<Integer> {

  @Override
  public Integer call() {
    AtomicInteger count = new AtomicInteger();
    IntStream.rangeClosed(0, 10).forEach(i -> {
      System.out.println(Thread.currentThread().getName() + " " + i);
      count.getAndIncrement();
    });

    return count.get();
  }

  public static void main(String[] args) {
    CreateThreadByImplementsCallable target = new CreateThreadByImplementsCallable();
    FutureTask<Integer> futureTask = new FutureTask<>(target);

    IntStream.rangeClosed(0, 10).forEach(i -> {
      System.out.println(Thread.currentThread().getName() + " 的循环变量 i 的值" + i);
      if (i == 8) {
        new Thread(futureTask, "有返回值的线程").start();
      }
    });

    try {
      System.out.println("有返回值线程的返回值:" + futureTask.get());
    } catch (InterruptedException | ExecutionException e) {
      e.printStackTrace();
    }
  }

}
复制代码

Through the above it can be seen, in fact, by implementing Runnablethe interface and implementation Callableto create the interface of these two threads basically the same way, the use of realization Runnableand Callablewhen mode interface to create a thread, the thread class only implements the interface can also inherit other classes ( PS:Java 单继承决定). In this way, multiple threads can share the same targetobject, so is ideal for multiple threads to handle the same situation with a resource. Another point is that, using inheritance Threadwhen you create multiple threads and the like, simple to prepare, if you need access to the current thread, you do not need to use Thread.currentThread()the method, used directly thisto obtain the current thread. If the use of these three ways to create a thread, if you create a closed frequently consumed in the actual project affect the performance of the system resources, and you can not use the thread pool thread when the thread back into the pool, then take a time from the thread pool, so our project development mainly use the thread pool, the thread pool can take a look at these two Java thread pool (a) , Java thread pool (II) .

Several state of the thread

A thread is a dynamic process of execution, it also has a process to produce death, in Java, a thread complete life cycle includes a total of five states from the following: New state (New) When using newkeywords and Threadclass or sub-class created after a thread object, the thread entered 新建状态, then it and other Java objects, just by the JVM allocates memory and initializes variable values of its members, it will remain in this state until a call to the object's startmethod.

Ready state (Runnable) When the thread object called startafter the method, the thread into the ready state. Ready thread will be placed in a ready queue, waiting for the JVM scheduler for scheduling. Thread a state of readiness at any time may be executed by the CPU scheduling.

Running state (Running) If the ready state execution is executed by the CPU scheduling, you can perform runthe method, then thread in the thread state. Thread running the most complex, it can become 阻塞状态, 就绪状态and 死亡状态. Note that thread becomes 运行状态the state before only 就绪状态.

Blocked (Blocked) thread becomes blocked because of some reason to abandon the use of the CPU, and temporarily stop operating, if performed sleep, suspendand other methods, after the release of resources occupied, the thread from 运行状态entering 阻塞状态. Waiting for the end of the sleep time or resources to get the re-entry device 就绪状态. Obstruction can be divided into the following three:

  1. Waiting for blocking in the 运行状态thread calls the waitmethod, the thread will enter等待阻塞状态
  2. Synchronous blocking when the thread acquire synchronizedsynchronization lock because the lock is in use by another thread synchronization fails, the thread will enter同步阻塞
  3. Other blocked by the calling thread sleepor joinwhen issuing the I / O request, the thread will enter the blocking state. When the sleeptimeout, joinwaiting thread terminates or expires, or I / O processing is completed, the thread back 就绪状态.

Death state (Dead) a in 运行状态the finished thread execution runmethod, or because other termination condition occurs, the thread will enter into 死亡状态the thread end of the life cycle. Circulation more threads represented by a variety of states is as follows:

thread-state-transfer.png

Thread common method

A method according to common thread source can be divided into two categories, one is inherited from Objectclass method, as follows:

method description
public final native void notify() Wake up a single thread waiting on this object's monitor so that it enters就绪状态
public final native void notifyAll() Wake up all threads waiting on this object's monitor so that it enters就绪状态
public final void wait() · Let the current thread is 等待阻塞状态, until another thread invokes the object's notifymethod or notifyAllmethods, the current thread wakes up, it will release the lock held
public final native void wait(long timeout) · Let the current thread is 等待阻塞状态, until another thread invokes the object's notifymethod or notifyAllmethods, the current thread wakes up
public final void wait(long timeout, int nanos) · Let the current thread is 等待阻塞状态, until another thread invokes the object's notifymethods or notifyAllmethod or some other thread interrupts the current thread, or a certain amount of time has exceeded the actual current thread wakes up

Another is the Threadclass definition method, as follows:

method description
public static native void yield() Suspend the currently executing thread object, and perform other thread, the yieldmethod does not release the lock
public static native void sleep(long millis) Thread to sleep (suspended) currently being executed within the specified number of milliseconds, sleepthe method does not release the lock
public final void join() When calling other threads in a program execution flow joinwhen the method, the calling thread will be blocked until the jointhread of execution has been completed
public void interrupt() To interrupt this thread, when this method is called, will immediately interrupt flag is set to thread true
public static boolean interrupted() ThreadA static method of the class, which returns a boolean indicating whether the current thread has been interrupted, interruptedthe method returns the interrupt flag in addition to outside, it also clears the interrupt flag (about to interrupt flag is set false)
public boolean isInterrupted() ThreadA class instance method that returns a boolean indicating whether the current thread has been interrupted, isInterruptedthe method simply returns the interrupt flag will not be clearly labeled terminal

Thread priority

Each Java thread has a priority, which helps determine the operating system thread scheduling order. Java thread priority is an integer whose value ranges 1(Thread.MIN_PRIORITY )~ 10(Thread.MAX_PRIORITY ). By default, each thread is assigned a priority NORM_PRIORITY(5). Has a higher priority thread is more important to the program, and should allocate processor resources prior to lower priority thread, Threadclass provides setPriorityand getPrioritymethods to change and get thread priority ( Note that: thread priority is not guaranteed thread the order of execution, but also very dependent on the platform ).


Reference article

Guess you like

Origin juejin.im/post/5dec6544e51d4557ed541c92