java high concurrency Series - Day 11: thread interrupted in several ways

high concurrency java series of 11 articles.

This paper discusses about the ways interrupted thread.

By controlling a variable thread interrupts

Code:

package com.itsoku.chat05;

import java.util.concurrent.TimeUnit;

/**
 * 微信公众号:路人甲Java,专注于java技术分享(带你玩转 爬虫、分布式事务、异步消息服务、任务调度、分库分表、大数据等),喜欢请关注!
 */
public class Demo1 {

    public volatile static boolean exit = false;

    public static class T extends Thread {
        @Override
        public void run() {
            while (true) {
                //循环处理业务
                if (exit) {
                    break;
                }
            }
        }
    }

    public static void setExit() {
        exit = true;
    }

    public static void main(String[] args) throws InterruptedException {
        T t = new T();
        t.start();
        TimeUnit.SECONDS.sleep(3);
        setExit();
    }
}

Code started a thread, run method of the thread has a cycle of death, whether internal controls exit through the exit value of the variable. TimeUnit.SECONDS.sleep(3);The main thread to sleep for 3 seconds, here Why TimeUnit? TimeUnit more convenient to use, can be controlled very clear sleep time, or converted to the underlying Thread.sleep achieved. There is a program focused on: volatile keyword, exit variables must pass this modification, if this removed, the program can not exit properly. volatile control the visibility of variables in multiple threads, the article on the front of volatile presentations, do not say that again here.

Thread that comes through the interrupt flag control

Sample code:

package com.itsoku.chat05;

import java.util.concurrent.TimeUnit;

/**
 * 微信公众号:路人甲Java,专注于java技术分享(带你玩转 爬虫、分布式事务、异步消息服务、任务调度、分库分表、大数据等),喜欢请关注!
 */
public class Demo2 {

    public static class T extends Thread {
        @Override
        public void run() {
            while (true) {
                //循环处理业务
                if (this.isInterrupted()) {
                    break;
                }
            }
        }
    }


    public static void main(String[] args) throws InterruptedException {
        T t = new T();
        t.start();
        TimeUnit.SECONDS.sleep(3);
        t.interrupt();
    }
}

Run the above program, the program can be completed normally. There is an internal thread interrupt flag, when the calling thread's interrupt () instance method, the thread would interrupt flag is set to true, () Gets the thread interrupt flag by instance method isInterrupted thread.

How to interrupt threads blocked

Sample code:

package com.itsoku.chat05;

import java.util.concurrent.TimeUnit;

/**
 * 微信公众号:路人甲Java,专注于java技术分享(带你玩转 爬虫、分布式事务、异步消息服务、任务调度、分库分表、大数据等),喜欢请关注!
 */
public class Demo3 {

    public static class T extends Thread {
        @Override
        public void run() {
            while (true) {
                //循环处理业务
                //下面模拟阻塞代码
                try {
                    TimeUnit.SECONDS.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static void main(String[] args) throws InterruptedException {
        T t = new T();
        t.start();
    }
}

Run the above code, the program can not find the end.

In the first to add a few knowledge:

  1. The calling thread's interrupt () instance method, interrupting the thread flag is set to true
  2. When a thread is blocked, the calling thread's interrupt () instance method, the internal thread will trigger InterruptedException exception, and will clear pending an internal thread (about to interrupt flag is set to false)

Then the above code can call the thread interrupt () method to initiate InterruptedException exception to interrupt the obstruction caused by sleep method, adjust the code as follows:

package com.itsoku.chat05;

import java.util.concurrent.TimeUnit;

/**
 * 微信公众号:路人甲Java,专注于java技术分享(带你玩转 爬虫、分布式事务、异步消息服务、任务调度、分库分表、大数据等),喜欢请关注!
 */
public class Demo3 {

    public static class T extends Thread {
        @Override
        public void run() {
            while (true) {
                //循环处理业务
                //下面模拟阻塞代码
                try {
                    TimeUnit.SECONDS.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    this.interrupt();
                }
                if (this.isInterrupted()) {
                    break;
                }
            }
        }
    }


    public static void main(String[] args) throws InterruptedException {
        T t = new T();
        t.start();
        TimeUnit.SECONDS.sleep(3);
        t.interrupt();
    }
}

operation result:

java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at java.lang.Thread.sleep(Thread.java:340)
    at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:386)
    at com.itsoku.chat05.Demo3$T.run(Demo3.java:17)

Program can be completed normally, analyze the code above, note a few:

  1. the main method called t.interrupt () method, in which the internal thread t interrupt flag is set to true
  2. Then triggers the run () method inside InterruptedException exception, so operating results in abnormal output, it says, and when the trigger abnormal InterruptedException when the internal thread interrupt flag will be cleared (becomes false), it is also in the catch call this.interrupt (); once , interrupt flag is set to false
  3. run () method to get through this.isInterrupted () thread interrupt flag, exits the loop (break)

to sum up

  1. When a thread is blocked state or to perform a blocking operation, you can use Thread.interrupt()way to interrupt the thread, pay attention this time will throw an InterruptedException anomaly, while the interrupt status will be reset (interrupted by the interrupt status to non-state )
  2. Internal loop, through a variable control signal as a thread is interrupted, attention needs to volatile variable modification
  3. The text of the ways you can combine the flexibility to use the thread interrupt control

java series of high concurrency

Series of high concurrency java, the total estimated there will be four or five articles to be concerned about the public number: javacode2018, get the latest articles.

Guess you like

Origin www.cnblogs.com/itsoku123/p/11199076.html
Recommended