sleep()与interrupt()

sleep():

1) sleep is a static method of the Thread class (Thread.sleep (1000), the specified time so that the thread to sleep, enter the blocking state.
2) SLEEP in fact, tell the system not to assign the thread a time slice during this time, so that the CPU time slice to another thread, which gives the other thread priority is lower than the chance of threads of execution, but also the opportunity to also give the same level or better level of threads of execution.
3) sleep be sure to catch the exception, because in the thread is blocked, and other objects likely to call its interrupt (), produce abnormal InterruptedException, if they do not catch the exception, then the thread will be aborted.

Simple code:

public class Threaddemo {
    public static void main(String[] args) {
        Runner2 r = new Runner2();
        //启动线程
        r.start();
        //主线程会休眠10秒钟再执行以下的程序,在休眠的过程中r线程每隔1秒打印一次,10秒之后,调用了r的interript,这时r线程抛出InterruptedException异常,return。
        try
        {
            Thread.sleep(10000);
        }catch (InterruptedException e) {
        }
        //中断线程
        r.interrupt();
        }
}

class Runner2 extends Thread{
    public void run() {
        while (true) {
            System.out.println("------");

            /**
             * sleep必须捕获异常
             * sleep()必须捕获异常,在sleep的过程中过程中有可能被其他对象调用它的interrupt(),
             * 产生InterruptedException异常,如果你的程序不捕获这个异常,线程就会异常终止,
             * 进入TERMINATED状态,如果你的程序捕获了这个异常,
             * 那么程序就会继续执行catch语句块(可能还有finally语句块)以及以后的代码。
            */
            
            try {
                Thread.sleep(1000);
            }catch (InterruptedException e) {
                return;
            }
        }
    }
}
    

interrupt()

1) First, to emphasize that, after the interrupt () method is called, does not immediately interrupt the current thread, so you need to monitor interrupt status, the interrupt state is to listen through InterruptedException exception is thrown when a thread calls interrupt () method, the thread will catch the exception, then you interrupted state, so by the blocked thread will launch the blocked state, it interrupts the current thread. For example the above procedures, when the main thread calls r.interrupt (), then the thread does not end, r thread throws InterruptedException exception and then interrupt thread.
After 2) only thread in wait, sleep, when one join three kinds blocking state, interrupt () method only works, otherwise the only other to perform the wait (), join (), sleep (), will throw InterruptedException exception.

Other interrupt method

1) Normal interruption, according to the normal logic thread finish, also stopped thread.
2) stop the forced stop, Thread.stop (), stop immediately, but may result in data is not synchronized, lack of resources, recycling and other issues, it has been abandoned.

Guess you like

Origin www.cnblogs.com/xushun/p/11229298.html