Thread definition, life cycle, commonly used method

The definition of a thread

1.1 Overview

A thread is a program of multiple execution paths, scheduling execution units present in the process relying

1.2 Definitions

1. Thread class inheritance

/**
 * 使用继承java.lang.Thread类的方式创建一个线程
 * 
 * @author DreamSea 2011-12-29 20:17:06
 */
public class ThreadTest extends Thread {

    /**
     * 重写(Override)run()方法 JVM会自动调用该方法
     */
    public void run() {
        System.out.println("I'm running!");
    }
}

Defects: do not recommend this method definitions thread, because the use of inheritance Thread way after the definition of the thread, you 不能再继承other classes, leading scalability program greatly reduced.

2. Implement Interface java.lang.Runnable

/**
 * 通过实现Runnable接口创建一个线程
 * @author DreamSea
 */
public class ThreadTest implements Runnable {
    public void run() {
            System.out.println("I'm running!");
    }
}

3. By Callable and Future
1. implement Callable interface call override method
2. Create a class object implement
3. Create an object class by implementing a FutureTask class object
4. Thread objects created by the class FutureTask last start

public class MyCallable implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        return 100;
    }

    public static void main(String[] args) {
        MyCallable callable = new MyCallable();
        FutureTask<Integer> task = new FutureTask<>(callable);
        new Thread(task).start();
        System.out.println("线程返回值:" + task.get());

    }

}

The difference between callable and runable: callable returns a value

二 interrupt

  1. If this thread is in the blocked state called its interrupt () method, then it's "interrupt status" will be cleared and will receive an InterruptedException exception.

For example, by a thread wait () into the blocked state and interrupts the thread through the interrupt (); call interrupt () will immediately interrupt the thread flag is set to "true", but because the thread is blocked, so that the "break mark "will immediately be cleared to false , at the same time, it will produce a InterruptedException exception.

  1. If a thread is blocked in the selector Selector, then () by which an interrupt interrupt; thread interrupt flag is set to true , and it will return from the selection operation immediately.
  2. If you do not belong to the previously mentioned case, then by interrupt () interrupt threads, it will interrupt flag is set to true .

Terminate the thread way

Terminate in a "blocked" thread

To exit the loop by capturing InterruptedException, interrupt threads

Termination is in the "running" in the thread

Termination is in the "running" in the thread through the "mark" mode. Which comprises 中断标记and 额外添加标记.
(01) by 中断标记terminating the thread

@Override
public void run() {
    while (!isInterrupted()) {
        // 执行任务...
    }
}

(02) through 额外添加标记.

private volatile boolean flag= true;
protected void stopTask() {
    flag = false;
}

@Override
public void run() {
    while (flag) {
        // 执行任务...
    }
}

Combine

@Override
public void run() {
    try {
        // 1. isInterrupted()保证,只要中断标记为true就终止线程。
        while (!isInterrupted()) {
            // 执行任务...
        }
    } catch (InterruptedException ie) {  
        // 2. InterruptedException异常保证,当InterruptedException异常产生时,线程被终止。
    }
}

Difference interrupted () and isInterrupted () of

interrupted () and isInterrupted () can be used to detect the object "interrupt flags."
The difference is, interrupted () In addition to returning interrupt flag outside it 还会清除中断标记(soon interrupt flag is set to false); and isInterrupted () 仅仅returns the interrupt flag

reference

Java multi-threading series - "Basics" 09 of the interrupt () and thread termination mode

Three thread state

image.png
Thread package includes the following five states.

  1. New state (New): After the thread object is created, entered the new state. For example, Thread thread = new Thread ().
  2. Ready state (Runnable): also known as "executable state." After the thread object is created, other thread calls the object start()方法, thereby to start the thread. For example, thread.start (). Thread a state of readiness at any time may be executed by the CPU scheduling.
  3. Running state (Running): CPU thread to obtain permission for execution. Note that, the thread can only be entered from the ready state to the running state.
  4. Blocked (Blocked): the thread is blocked for some reason to give up the right to use CPU temporarily stops running. Until the thread into the ready state, a chance to go running. Case of obstruction of sub- three kinds :
    (01) blocking wait - wait by the calling thread () method, thread to wait for the completion of a job.
    (02) synchronous blocking - a thread get synchronized synchronous lock failure (because the lock was occupied by another thread), it will enter synchronous blocking state.
    (03) other obstruction - through the sleep () or join the calling thread () or issue an I / O request, the thread into the blocked state. When sleep () timeout, the Join () or a timeout wait for a thread to terminate, or I / O processing is completed, the thread into the ready state again.
  5. Death state (Dead): thread execution is over or due to abnormal exit the run () method, the thread end of the life cycle.

Why wait for the next state is locked Blocked Blocked?
Because the wait must have been in 同步块中use, so after being awakened, it will lock into the pool to wait.

Reference: the Java multithreading series - "The Basics" The basic concept of 01

Four common methods

sleep和wait

  1. sleep () does not release the lock (will release cpu resources); wait()会释放对象锁after wake-up, the wait continues below.
  2. wait 必须在同步块中executed otherwise it will throw an exception. Will notify specified or notifyAlll or sleep time to wake up (three cases)
  3. wait is 对象(so will release the object lock), slepp static method of the Thread

reference

Java Thread (thread) Detailed case of the difference between sleep and wait

Published 82 original articles · won praise 1 · views 1834

Guess you like

Origin blog.csdn.net/m0_38060977/article/details/104079428