Java多线程编程核心技术之---停止线程

在Java中有三种方法可以终止正在运行的线程
1,使用退出标志使线程退出,也就是run方法完成后线程终止
2,使用stop方法强行终止线程,但不推荐,因为stop和suspend及resume一样,都是作废过期的方法,使用它们会产生不可预料的效果
3,使用interrupt中断线程(只是打了一个停止标记,不是真正停止)

interrupt方法停止线程操作

package com.test.Thread.t7;
/**
 * interrupt方法停止线程
 * 使用interrupt中断线程(只是打了一个停止标记,不是真正停止)
 * @author admin
 * 2017年4月13日
 */

public class MyThread2 extends Thread{

    @Override
    public void run() {
        // TODO Auto-generated method stub
        super.run();
        for (int i = 0; i <5000000; i++) {
            System.out.println("i==="+(i+1));
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThread2 m2=new MyThread2();
        m2.start();
        Thread.sleep(2000);
        m2.interrupt(); //线程并没有停止 
    }
}

如何判断线程状态是否停止的?
Java sdk中Thread.java类有两个方法可以判断
this.isInterrupted(); 测试线程是否中断
this.interrupted(); 测试当前线程是否已经中断

    public static void main(String[] args) {
        Thread.currentThread().interrupt();
        System.out.println("是否停止=1 "+Thread.interrupted());
        System.out.println("是否停止=2 "+Thread.interrupted());
        System.out.println("end!");
    }
    运行后输出
    是否停止=1 true
    是否停止=2 false
    end!
    从上述结果看 方法interrupted的确判断出当前线程是否是停止状态 为什么第二个布尔值是fasle?官方帮助文档是这样解释的 如果连续两次调用该方法 第二次会返回false(第一次调用完成后会清除中断状态)
    isInterrupted方法正好相反 不会清除中断状态
线程的暂停与恢复
suspend()方法暂停线程
resume()方法恢复线程的执行
缺点:容易造成公共的同步的对象的独占,使得其它线程无法访问公共的同步对象

package com.test.Thread.t8;
/**
 * 使用suspend与resume方法的使用
 * suspend()方法暂停线程
 * resume()方法恢复线程的执行
 * @author admin
 * 2017年4月13日
 */
public class MyThread extends Thread{
    private  long i=0;


    public long getI() {
        return i;
    }


    public void setI(long i) {
        this.i = i;
    }


    @Override
    public void run() {
        while(true){
            i++;
        }
    }
}



package com.test.Thread.t8;
/**
 * 使用suspend与resume方法的使用
 * suspend()方法暂停线程
 * resume()方法恢复线程的执行
 * @author admin
 * 2017年4月13日
 */
public class Run {

    public static void main(String[] args) throws InterruptedException {
        MyThread thread=new MyThread();
        thread.start();
        Thread.sleep(5000);
        //A
        thread.suspend(); //暂停
        System.out.println("A="+System.currentTimeMillis()+"  i=="+thread.getI());
        Thread.sleep(5000);
        System.out.println("A="+System.currentTimeMillis()+"  i=="+thread.getI());
        //B
        thread.resume(); //恢复执行
        Thread.sleep(5000);
        //C
        thread.suspend(); //暂停
        System.out.println("B="+System.currentTimeMillis()+"  i=="+thread.getI());
        Thread.sleep(5000);
        System.out.println("B="+System.currentTimeMillis()+"  i=="+thread.getI());

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值