Java common knowledge Summary (⑬) - Thread

Java multi-threaded programming to provide built-in support. A thread refers to a single control flow of a process sequence, a process can be complicated by a plurality of threads, each thread in parallel to perform different tasks.

Multithreading is a special form of multi-tasking, multi-threading, but use a smaller resource overhead.

Another term is defined herein and the associated thread - processes: a process including the allocation of memory space by the operating system, comprising one or more threads. A separate thread can not exist, it must be part of the process. A process has been run, to end until after all of the non-daemon threads have finished running.

Multithreading can meet programmers to write efficient programs to achieve full use of the CPU.

A. A thread of life cycle

A thread is a dynamic process of execution, it also has a process from creation to death.

New State : After establishing a thread object and the new keyword Thread class or subclass, the thread is in the new state of the object. It remains in this state until program start () this thread.

** ready state: ** When a thread object to call the start () method, the thread into the ready state. Ready thread in the ready queue, waiting to schedule the JVM thread scheduler.

Operating status : If the thread gets ready state of the CPU resources, you can perform run (), the thread will be running at this time. Thread running the most complex, it can become blocked state, ready state, and the state of death.

Blocking state : If a thread is executed after sleep (sleep), suspend (pending) and other methods, the loss of occupied resources, the thread enters the blocked state from running. In the sleep time has come to get equipment or resources may re-enter the ready state. It can be divided into three types:

  • Waiting for blocking: execution threads running state of wait () method, the thread is blocked waiting to enter the state.
  • Synchronous blocking: get synchronized thread synchronization lock failure (because another thread synchronization lock is occupied).
  • Other blocking: Issue the I / O request, the thread will enter the state by blocking the calling thread sleep () or join (). When sleep () timeout, the Join () wait for a thread to terminate or a timeout, or I / O processing is completed, the thread into the ready state again.

The state of death : a thread to complete the task of running the state or other termination condition occurs, the thread switches to the termination of the state.

Thread.run () and Thread.start () the difference between :

  • start () method to start a thread, truly multi-threaded operation. Then without waiting for the run method body code is completed, you can proceed directly to the following code; to start a thread by calling start Thread class () method, then this thread is in the ready state and is not running. Then this method calls the Thread class run () to complete its run operation, where the method run () is called thread body, which contains the contents of this thread to be executed, ending the Run method to run this thread to terminate. Then CPU rescheduling other threads.
  • Call the run () method as a regular method of way. To perform a procedure or order, to wait for the run method after the implementation thereof, to proceed with the following code; this program, only the main thread is a thread, which is only one program execution path, so there is no purpose to write threads.

II. The difference between sleep and wait

These two methods are from different categories: sleep from Thread class, Object class from the wait. sleep is a static method of the Thread, who called who go to bed, even if the calling method b of sleep in a thread, in fact, still a go to sleep, let b threads sleep sleep in the code to call the b's.

Lock: sleep is the most important method is not release the lock, the lock release wait method, so that other threads may be used or a method of a synchronization control block. ** sleep not to sell the system resources; wait is waiting to enter the thread pool to wait and let the system resources, other threads can occupy CPU. ** usually wait will not increase the time limit, because you run a resource wait thread is not enough, then it is useless to wait for the other thread calls notify / notifyAll wakes up all the threads waiting in the pool, will enter the ready queue waiting OS distribution system resources. sleep (milliseconds) can be specified time so it automatically wake up, can only be called if less than interrupt () forcibly interrupted. Role Thread.sleep (0) is "operating system immediately triggers a re-CPU competition."

Range: wait, notify, and notifyAll only synchronization control method for controlling the synchronization or a block (the synchronized) used in it, but can be used anywhere sleep:

   synchronized(x){ 
      x.notify() 
     //或者wait() 
   }
复制代码

Priority III. Thread

Each Java thread has a priority, which helps determine the operating system thread scheduling order.

Java thread priority is an integer which ranges from 1 (Thread.MIN_PRIORITY) - 10 (Thread.MAX_PRIORITY).

By default, each thread is assigned a priority NORM_PRIORITY (5).

Thread with a higher priority is more important to the program, and should allocate processor resources prior to lower priority thread. However, the order does not guarantee thread priority thread of execution, but also very dependent on the platform.

IV. Creating a thread

Java provides three ways to create threads:

  • By implementing Runnable interface;
  • Through inheritance Thread class itself;
  • Create a thread through Callable and Future.

By implementing Runnable interface

class RunnableDemo implements Runnable {
   private Thread t;
   private String threadName;
   
   RunnableDemo( String name) {
      threadName = name;
      System.out.println("Creating " +  threadName );
   }
   
   public void run() {
      System.out.println("Running " +  threadName );
      try {
         for(int i = 4; i > 0; i--) {
            System.out.println("Thread: " + threadName + ", " + i);
            // 让线程睡眠一会
            Thread.sleep(50);
         }
      }catch (InterruptedException e) {
         System.out.println("Thread " +  threadName + " interrupted.");
      }
      System.out.println("Thread " +  threadName + " exiting.");
   }
   
   public void start () {
      System.out.println("Starting " +  threadName );
      if (t == null) {
         t = new Thread (this, threadName);
         t.start ();
      }
   }
}
 
public class TestThread {
 
   public static void main(String args[]) {
      RunnableDemo R1 = new RunnableDemo( "Thread-1");
      R1.start();
      
      RunnableDemo R2 = new RunnableDemo( "Thread-2");
      R2.start();
   }   
}
复制代码

Through inheritance Thread class itself

class ThreadDemo extends Thread {
   private Thread t;
   private String threadName;
   
   ThreadDemo( String name) {
      threadName = name;
      System.out.println("Creating " +  threadName );
   }
   
   public void run() {
      System.out.println("Running " +  threadName );
      try {
         for(int i = 4; i > 0; i--) {
            System.out.println("Thread: " + threadName + ", " + i);
            // 让线程睡眠一会
            Thread.sleep(50);
         }
      }catch (InterruptedException e) {
         System.out.println("Thread " +  threadName + " interrupted.");
      }
      System.out.println("Thread " +  threadName + " exiting.");
   }
   
   public void start () {
      System.out.println("Starting " +  threadName );
      if (t == null) {
         t = new Thread (this, threadName);
         t.start ();
      }
   }
}
 
public class TestThread {
 
   public static void main(String args[]) {
      ThreadDemo T1 = new ThreadDemo( "Thread-1");
      T1.start();
      
      ThreadDemo T2 = new ThreadDemo( "Thread-2");
      T2.start();
   }   
}
复制代码

Create a thread through Callable and Future

  • Create Callable interface implementation class, and implements call () method, the call () method as a thread of execution, and return values.
  • Callable create an instance of the implementation class, using packaging Callable FutureTask class object, which object encapsulates FutureTask Callable object of the call () method returns the value.
  • Use FutureTask Thread object as a target object to create and start a new thread.
  • Call FutureTask object get () method to obtain the return value after the end of the sub-thread execution.
public class CallableThreadTest implements Callable<Integer> {
    public static void main(String[] args)  
    {  
        CallableThreadTest ctt = new CallableThreadTest();  
        FutureTask<Integer> ft = new FutureTask<>(ctt);  
        for(int i = 0;i < 100;i++)  
        {  
            System.out.println(Thread.currentThread().getName()+" 的循环变量i的值"+i);  
            if(i==20)  
            {  
                new Thread(ft,"有返回值的线程").start();  
            }  
        }  
        try  
        {  
            System.out.println("子线程的返回值:"+ft.get());  
        } catch (InterruptedException e)  
        {  
            e.printStackTrace();  
        } catch (ExecutionException e)  
        {  
            e.printStackTrace();  
        }  
  
    }
    @Override  
    public Integer call() throws Exception  
    {  
        int i = 0;  
        for(;i<100;i++)  
        {  
            System.out.println(Thread.currentThread().getName()+" "+i);  
        }  
        return i;  
    }  
}
复制代码

Comparison of three methods to create threads

  • When using create multiple threads to achieve Runnable, Callable interface means, Thread class implements Runnable interface or just Callable interface, you can also inherit from other classes.
  • When you create a multi-threaded use inheritance Thread class, simple to prepare, if you need access to the current thread, you do not need to use Thread.currentThread () method, the direct use this to get the current thread.

Several major concepts V. thread

In multi-threaded programming, you need to understand the following concepts:

  • Thread Synchronization
  • Inter-thread communication
  • Thread deadlock
  • Thread control: suspend, stop and resume

VI. Multithreaded use

The key to effective use of multithreading is to understand the program is executed concurrently rather than serially performed. For example: There are two sub-programs require concurrent execution, this time you need to take advantage of multi-threaded programming.

By the use of multiple threads, you can write a very efficient program. However, please note that if you create too many threads, the efficiency of program execution is actually reduced, rather than enhanced.

Remember, context switching overhead is also very important, if you create too many threads, CPU time spent in context switching time than the execution of the program!

Guess you like

Origin juejin.im/post/5e64eb896fb9a07cc10ab03e