美文网首页
java线程控制的基本方法(一)以及interrupt、inte

java线程控制的基本方法(一)以及interrupt、inte

作者: exmexm | 来源:发表于2017-04-25 19:43 被阅读0次
    线程状态转换

    //判断线程是否还活着,即线程是否还未终止
    isAlive()

    //获得线程的优先级数值
    getPriority()

    //设置线程的优先级数值
    setPriority()

    //指定当前线程睡眠指定的毫秒数
    Thread.sleep()

    //调用某线程的该方法,将当前线程与该线程“合并”,即等该线程结束,再恢复当前线程的运行。
    join()

    //让出CPU,当前线程进入就绪队列,等待调度。
    yield()

    //当前线程进入对象的wait pool
    wait()

    //唤醒对象的wait pool中的一个/所有等待等待线程
    notify() / notifyAll()

    参考:http://www.w2bc.com/Article/62802
    区分好interrupt、interrupted、isInterrupted:

    interrpupted()方法是Thread类的静态方法;第一次使用该方法如果已经中断,第二次使用该方法则会取消中断。
    interrupt()是对象实例方法
    在使用了interrupt()后,线程会将中断标志设置为true。如果线程处于waiting或timed_waiting状态,则会产生一个InterruptedException。
    isInterrupted()是对象实例方法
    在使用isInterrupted()后,如果中断标志为true则返回true。

    代码

    
    import java.util.*;
    
    public class TestInterrupt2 {
    
        public static void main(String[] args) {
            Thread3 t = new Thread3();
            t.start();
            try {
                /*main方法被睡眠了10000毫秒,与此同时t线程继续运行
                 *正常的结果是t每隔1s输出当前的日期
                 *主方法睡眠10000ms后,继续运行,interrupt打断t线程。*/
                Thread.sleep(10000);   
            } catch(InterruptedException e) {
                
            }
            t.interrupt();
        }
    
    }
    
    
    class Thread3 extends Thread {
        public void run() {
            
            while (true) {
                System.out.println(" ======" + new Date() + "========");
                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                    return;
                }
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:java线程控制的基本方法(一)以及interrupt、inte

          本文链接:https://www.haomeiwen.com/subject/yewvzttx.html