Java multi-threading (Thread class)

The concept is simple to understand

  1. Program (programm)
  • The concept: is to accomplish a specific task, with the collection of a set of instructions written in a language. It refers to a period of static code.
  1. Process (process)
  • Concept: process, or a running program once the implementation of the program.
  • Description: As the process of resource allocation units at run-time system will assign a different memory area for each process
  1. Thread (thread)
  • The concept: The process can be further refined into threads, is an execution path of an internal program.
  • Description: As the thread scheduling and execution units, each thread owned independent runtime stack and program counter (pc), small thread switching overhead.

Here Insert Picture Description
Added:
Memory structure:
Here Insert Picture Description

The process can be refined into multiple threads.
Each thread has its own independent: stack, program counter
multiple threads share the same process structure: Method district, heap.

  1. Understand the single-core CPU and multi-core CPU
    single-core CPU, in fact, it is a multi-threaded false, because in a time unit, can only perform tasks a thread. For example: Although multiple lanes, but only one toll station staff in charge, only received a fee to pass, then the CPU is like the cashier. If someone does not want to pay, you can charge him "hang" (Hanging him, so he figured out, ready money, go fee.) But because the CPU time units are particularly short, so do not feel out .
    If this is the case of multi-core, in order to better play to the efficiency of multi-threaded. (Now the servers are multicore)
  • A Java application java.exe, in fact, at least three threads: main () main thread, gc () thread garbage collection, exception handling thread. Of course, if an exception occurs, it will affect the main thread.
  1. Parallel and concurrent understanding
    parallel : multiple CPU simultaneously perform multiple tasks. For example: more than one person at the same time doing different things.
    Concurrency : a CPU (using the time slice) simultaneously perform multiple tasks. For example: spike, more than one person to do the same thing

Two ways to create multi-threaded

One way: inheritance Thread class.

  1. Creating a Thread class inherits from a subclass
  2. Rewrite run Thread class () -> operating statement in this thread of execution run () in
  3. Create an object of a subclass of the Thread class
  4. This object calls start (): ① ② start the current thread that called the current thread's run ()

Shows two things:
One problem: we start a thread, you must call the start (), can not call the run () way to start the thread.
Question two: If we start a thread, you must re-create a subclass of the Thread object, call the object's start ().

Second way: implementation of the Runnable interface.

  1. Create a class that implements the Runnable interface
  2. Implement the abstract class to implement the method of Runnable: run ()
  3. Create an object implementation class
  4. This object is passed as an argument to the constructor of the Thread class, create an object class Thread
  5. Call start through the object of the Thread class ()

Comparison of two ways:

  • Development: preferences: implement Runnable way

  • the reason:

    1. Limitations of single inheritance is not the way to achieve the class
    1. The way to achieve better suited to handle cases where multiple threads share data.
  • 联系:public class Thread implements Runnable

  • Similarities: Both approaches need to override run (), a logical statement will be executed in the thread run () in.
    目前两种方式,要想启动线程,都是调用的Thread类中的start()。

Thread class

Thread class commonly used methods:

 1. start():启动当前线程;调用当前线程的run()
 2. run(): 通常需要重写Thread类中的此方法,将创建的线程要执行的操作声明在此方法中
 3. currentThread():静态方法,返回执行当前代码的线程
 4. getName():获取当前线程的名字
 5. setName():设置当前线程的名字
 6. yield():释放当前cpu的执行权
 7. join():在线程a中调用线程b的join(),此时线程a就进入阻塞状态,直到线程b完全执行完以后,线程a才结束阻塞状态。
 8. stop():已过时。当执行此方法时,强制结束当前线程。
 9. sleep(long millitime):让当前线程“睡眠”指定的millitime毫秒。在指定的millitime毫秒时间内,当前线程是阻塞状态。
 10. isAlive():判断当前线程是否存活

Thread priority:
1.

  • MAX_PRIORITY:10
  • MIN _PRIORITY:1
  • NORM_PRIORITY: 5 -> default priority

2. How to get and set the priority of the current thread:

  • getPriority (): Get the Thread Priority

  • Priority thread: setPriority (int p)

  • Description: High-priority threads to execute the right to seize the low priority thread cpu's. But only in terms of probability, it is carried out at high priority thread high probability. When that does not mean only high-priority thread executing the low-priority thread before the execution.

Thread communication: wait () / notify () / notifyAll (): This method is defined in three Object class.

Added: Classification threads
one is a daemon thread, one is user threads.

Thread of the life cycle

Here Insert Picture Description
Description:

  1. Life Cycle focus on two concepts: the state, the appropriate method
  2. Attention: state a-> b states: Which method is executed (callback method)
    a method invocation initiative: state a-> b state
  3. Obstruction: a temporary state, not as the final status
    of death: the final state.

Thread synchronization mechanism

Portal: here

Thread communication

  1. Thread communication method related to three :
  • wait (): When you perform this method, the current thread into the blocked state, and the release of sync monitors.
  • notify (): When you perform this method, you will wake up a thread of wait. If there are multiple threads wait, they wake up that high priority.
  • notifyAll (): When you perform this method, you will wake up all the wait thread.
  1. Description :
  • 1.wait (), notify (), notifyAll () method must be used in three blocks or synchronization code synchronization method.
  • 2.wait (), notify (), notifyAll () method is called three must be synchronized block synchronization or synchronization monitor method.
  • Otherwise, there will be an exception IllegalMonitorStateException
  • 3.wait (), notify (), notifyAll () method is defined in three class java.lang.Object.
  1. Interview questions :
    interview questions: sleep () and wait () the similarities and differences?
  • 1. same point: Once the method is performed, so that the current thread may enter the blocking state.
  • 2. Different points: 1) the method declaration two different positions: the Thread class declaration sleep (), Object class declaration wait ()
  •      2)调用的要求不同:sleep()可以在任何需要的场景下调用。 wait()必须使用在同步代码块或同步方法中
    
  •      3)关于是否释放同步监视器:如果两个方法都使用在同步代码块或同步方法中,sleep()不会释放锁,wait()会释放锁。
    
  1. Summary lock release operation :
    Here Insert Picture Description
    summary will not release the lock operation:
    Here Insert Picture Description

JDK5 way to create new threads

A new way: to achieve Callable interface. - JDK 5.0 new

//1.创建一个实现Callable的实现类
class NumThread implements Callable{
    //2.实现call方法,将此线程需要执行的操作声明在call()中
    @Override
    public Object call() throws Exception {
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
            if(i % 2 == 0){
                System.out.println(i);
                sum += i;
            }
        }
        return sum;
    }
}
public class ThreadNew {
    public static void main(String[] args) {
        //3.创建Callable接口实现类的对象
        NumThread numThread = new NumThread();
        //4.将此Callable接口实现类的对象作为传递到FutureTask构造器中,创建FutureTask的对象
        FutureTask futureTask = new FutureTask(numThread);
        //5.将FutureTask的对象作为参数传递到Thread类的构造器中,创建Thread对象,并调用start()
        new Thread(futureTask).start();

        try {
            //6.获取Callable中call方法的返回值
            //get()返回值即为FutureTask构造器参数Callable实现类重写的call()的返回值。
            Object sum = futureTask.get();
            System.out.println("总和为:" + sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

}

Description:

  • Create multi-threaded way to understand how to achieve Callable interface, multi-threaded Runnable interface to create powerful than achieved?
  1. call () can return a value.
  2. call () can throw an exception, the outside of the capture operation, abnormality information acquired
  3. Callable support generics

New way: using a thread pool

class NumberThread implements Runnable{

    @Override
    public void run() {
        for(int i = 0;i <= 100;i++){
            if(i % 2 == 0){
                System.out.println(Thread.currentThread().getName() + ": " + i);
            }
        }
    }
}
class NumberThread1 implements Runnable{

    @Override
    public void run() {
        for(int i = 0;i <= 100;i++){
            if(i % 2 != 0){
                System.out.println(Thread.currentThread().getName() + ": " + i);
            }
        }
    }
}
public class ThreadPool {

    public static void main(String[] args) {
        //1. 提供指定线程数量的线程池
        ExecutorService service = Executors.newFixedThreadPool(10);
        ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;
        //设置线程池的属性
//        System.out.println(service.getClass());
//        service1.setCorePoolSize(15);
//        service1.setKeepAliveTime();


        //2.执行指定的线程的操作。需要提供实现Runnable接口或Callable接口实现类的对象
        service.execute(new NumberThread());//适合适用于Runnable
        service.execute(new NumberThread1());//适合适用于Runnable

//        service.submit(Callable callable);//适合使用于Callable
        //3.关闭连接池
        service.shutdown();
    }

}

Description:

  • Benefits:
    1. To improve the speed of response (reduction in the time to create a new thread)
    2. reduce resource consumption (thread pool thread to reuse, do not need to create each time)
    3. facilitate thread management
  •  corePoolSize:核心池的大小
    
  •  maximumPoolSize:最大线程数
    
  •  keepAliveTime:线程没任务时最多保持多长时间后会终止
    

Interview questions: create multi-threaded Java, there are several ways? Four.

Published 73 original articles · won praise 0 · Views 1237

Guess you like

Origin blog.csdn.net/qq_38605145/article/details/105105425