This article is a summary of the study of the article on the network, thank you for your selfless sharing.
1 java program, only if all of its threads are executed at the end (more specifically, all non-daemon threads end or a thread calls system .exit () When span lang= "ZH-CN" style= "Font-family:simsun" > method, it will not end running. Sometimes you need to end a thread in order to terminate the program, or when the user of the program wants to cancel a thread The task that the object is doing.
2 , Java The interrupt mechanism is provided to inform the thread that we want to end it. The nature of the interrupt mechanism is that the thread needs to check whether it is interrupted, and it can decide whether to end the request accordingly. Therefore, the thread can ignore the interrupt request and continue running.
3,Threadclass also has other methods that can check if a thread is interrupted. For example, a static methodinterrupted()to check if the running thread is interrupted. isinterrupted ()and theinterrupted ()method has a very important difference. The first one doesn't change .interruptedproperty value, but the second one is set tofalse. interrupted ()method is a static method, it is recommended to use theisinterrupted ()method.
Here is the code implementation
Package chapter;/** * * <p> * Description: Interrupt of Thread * </p> * @author Zhangjunshuai * @version 1.0 * Create Date: 2014-8-11 a.m. 11:09:55 * Project Name:java7thread * * <pre> * Modification History: * Date Author Version Description *--------------------------------------------- --------------------------------------------------------------* Lastchange: $Date:: $ $Author: $ $Rev: $ * </pre> * */public class Primegenerator extends thread{@Overridepublic void Run () {//TODO Aut O-generated method Stublong Number = 1l;while (true) {if (IsPrime (number)) {System.out.printf ("number%d is prime\n", number);} if (isinterrupted ()) {System.out.printf ("The Prime Generator has been interrupted"); return;} number++;}} /** * <p> * </p> * @author Zhangjunshuai * @date 2014-8-11 PM 2:48:31 * @param number * @return */private Boole An IsPrime (long number) {if (number <=2) {RETUrn true;} for (long i=2; i<number;i++) {if ((number%i) ==0) {return false;}} return true;}}
Main program Call
Package Chapter;public class Main3 {/** * <p> * </p> * @author Zhangjunshuai * @date 2014-8-11 Morning 11:20:15 * @p Aram args */public static void main (string[] args) {//TODO auto-generated method Stubthread task = new Primegenerator (); t Ask.start (); try {thread.sleep ();} catch (Interruptedexception e) {e.printstacktrace ();} Task.interrupt ();}}
Experimental results
Reference:
concurrent programming Network