Java多线程编程-停止线程 暂停线程

来源:互联网 发布:网络小胖大卡通图片 编辑:程序博客网 时间:2024/06/04 17:55

一 停止线程

停止线程是在多线程开发中很重要的技术点,个人总结停止线程有下面三种方法:

1.使用interrupt()方法停止线程

1.1 单独用interrupt()是不能停止线程的,此方法仅仅是在当前线程中打了一个停止线程的标记,并不是真正的停止线程,当运行下面的测试代码时,会发现,线程并未停止。

/** *  * *<p>Description:测试Interrupt方法停止线程</p> * * @author:SongJia * * @date: 2017-4-5上午11:14:38 * */public class TestThread extends Thread{    @Override    public void run() {        super.run();        for (int i = 0; i < 50000; i++) {            System.out.println("i:"+i);        }    }}
public class Run {    public static void main(String[] args) throws InterruptedException {        TestThread thread = new TestThread();        thread.start();        Thread.sleep(2000);        thread.interrupt();        System.out.println("THE thread whether stop:"+thread.isInterrupted());    }}

判断线程是否停止的两个方法:
this.interrupted():测试当前线程是否已中断
测试当前线程是否已经中断,线程的中断状态由该方法清除,也就是如果连续两次调用该方法,则第二次调用将返回false(在第一次调用已清除了其中断状态之后,且第二次调用检验完中断状态前,当前线程再次中断的情况除外)。

this.isInterrupted():测试线程Thread对下岗是否已是中断状态
不清除状态标志

1.2 使用interrupt()与return结合实现线程的停止

/** *  * *<p>Description:测试Interrupt方法和retun停止线程</p> * * @author:SongJia * * @date: 2017-4-5上午11:36:57 * */public class TestThread extends Thread{    @Override    public void run() {        while (true) {            if(TestThread.interrupted()){                System.out.println("The thread is stop!");                return;            }            System.out.println("time="+System.currentTimeMillis());        }    }}
public class Run {    public static void main(String[] args) throws InterruptedException {        TestThread thread = new TestThread();        thread.start();        Thread.sleep(2000);        thread.interrupt();    }}

这里写图片描述
由上图看出,使用interrupt()与return结合实现线程的停止


2 使用抛异常的方法停止线程

/** *  * *<p>Description:使用异常停止线程</p> * * @author:SongJia * * @date: 2017-4-5下午2:28:21 * */public class TestThread extends Thread{    @Override    public void run() {        super.run();        try {            for (int i = 0; i < 500000; i++) {                if(this.interrupted()){                    System.out.println("The Thread had alreday stop,exit!");                    throw new Exception();                }                System.out.println("i="+(i+1));            }            for (int j = 0; j < 50; j++) {                System.out.println("J="+(j+1));            }        } catch (Exception e) {            System.out.println("TestThread Catch ");            e.printStackTrace();        }    }}
public class Run {    public static void main(String[] args) throws InterruptedException {        try {            TestThread myThread = new TestThread();            myThread.start();            Thread.sleep(2000);            myThread.interrupt();        } catch (Exception e) {            System.out.println("Main Catch");            e.printStackTrace();        }        System.out.println("End");    }}

这里写图片描述

由程序运行结果图可以看出,在TestThread 类中,第二个for循环的代码没有执行,证明用抛异常的方法停止线程成功。


3 使用stop()方法停止线程

3.1 Thread.stop()已经被废除,为什么不建议使用呢,一个重要原因就是调用Thread.stop()方法停止线程时,会对锁定的对象进行“解锁”,导致数据得不到同步处理,出现数据不一致的问题。

/** *  * *<p>Description:测试Stop()方法停止线程</p> * * @author:SongJia * * @date: 2017-4-5上午11:52:22 * */public class SynchronizedObject {    private String username="xiaoming";    private String password="123456";    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    synchronized public void printString(String name,String pass){        try {            this.username=name;            Thread.sleep(100000);            this.password=pass;        } catch (InterruptedException e) {            e.printStackTrace();        }    }}
public class MyThread extends Thread{    public SynchronizedObject object;    public MyThread(SynchronizedObject object){        super();        this.object=object;    }    @Override    public void run() {        object.printString("xiaohong", "654321");    }}
public class Run {    public static void main(String[] args) throws InterruptedException {        SynchronizedObject object = new SynchronizedObject();        MyThread myThread = new MyThread(object);        myThread.start();        Thread.sleep(100);        myThread.stop();        System.out.println(object.getUsername()+"=:"+object.getPassword());    }}

这里写图片描述

由上图看出,使用stop()停止线程,出现了数据问题,所以,这个方法不建议大家使用。
顺便说一下,调用stop()方法时会抛出java.lang.ThreadDeath异常,但是在通常情况下,此异常不需要显式地捕捉。

二 暂停线程

在java多线程编程中,暂停线程意味着此线程还可以恢复运行,可以用suspend()方法暂停线程,使用resume()方法恢复线程的执行,但是,使用suspend()与resume()方法时,如果使用不当,也会出现很多问题。
2.1 线程的暂停与恢复

/** *  * *<p>Description:测试线程的暂停与恢复</p> * * @author:SongJia * * @date: 2017-4-5下午3:03:17 * */public class TestThread extends Thread{    private  int  i= 0;    public int getI() {        return i;    }    public void setI(int i) {        this.i = i;    }    @Override    public void run() {        while (true) {            i++;        }    }}
public class Run {    public static void main(String[] args) throws InterruptedException {        TestThread thread = new TestThread();        thread.start();        Thread.sleep(2000);        thread.suspend();        System.out.println("The Thread had alreday suspend:"+thread.getI());        Thread.sleep(2000);        System.out.println("The Thread had alreday suspend:"+thread.getI());        thread.resume();        System.out.println("The Thread resume:"+thread.getI());        Thread.sleep(2000);        thread.suspend();        System.out.println("The Thread had alreday suspend:"+thread.getI());        Thread.sleep(2000);        System.out.println("The Thread had alreday suspend:"+thread.getI());    }}

2.2 suspend()与resume()方法的缺点-线程独占
使用suspend()与resume()方法时,如果使用不当,极易造成公共的同步对象的独占,使其他线程无法访问公共同步对象

/** *  * *<p>Description:测试线程的独占</p> * * @author:SongJia * * @date: 2017-4-5下午3:39:46 * */public class PrintStr {    synchronized public void printString(){        System.out.println("Begin");        if(Thread.currentThread().getName().equals("a")){            System.out.println("a thread suspend");            Thread.currentThread().suspend();        }        System.out.println("End");    }}
public class Run {    public static void main(String[] args) throws InterruptedException {        final PrintStr printStr = new PrintStr();        Thread thread = new Thread(){            @Override            public void run() {                printStr.printString();            }        };        thread.setName("a");        thread.start();        thread.sleep(1000);        Thread threadTwo = new Thread(){            @Override            public void run() {                System.out.println("ThreadTwo is running ");                System.out.println("The method printString() had already locked with \"a\" thread,forever suspend");                printStr.printString();                System.out.println("threadTwo is end");            }        };        threadTwo.start();    }}

这里写图片描述
由上面示例程序的运行结果可以看出,“a”线程在执行printString()方法时执行了suspend()方法,独占了printString()方法,导致threadTwo 线程无法访问printString()方法。

2.3 在使用suspend()与resume()方法时也容易出现因为线程暂停而导致数据不同步的情况,这个情况和stop停止线程导致数据不同步的情况类似。

/** *  * *<p>Description:测试线程暂停而导致的数据不同步</p> * * @author:SongJia * * @date: 2017-4-5下午3:41:13 * */public class User {    private String name="xiaoming";    private String password="123456";    public void setValue(String name,String password){        this.name=name;        if(Thread.currentThread().getName().equals("a")){            System.out.println("\"a\" thread stop");            Thread.currentThread().suspend();        }        this.password=password;    }    public void printUsernameAndPassword(){        System.out.println(name+":"+password);    }}
public class Run {    public static void main(String[] args) throws InterruptedException {        final User user = new User();        Thread thread = new Thread(){            @Override            public void run() {                user.setValue("xiaohong", "654321");            }        };        thread.setName("a");        thread.start();        thread.sleep(1000);        Thread threadTwo = new Thread(){            @Override            public void run() {                user.printUsernameAndPassword();            }        };        threadTwo.start();    }}

这里写图片描述
由上面示例程序的运行结果可以看出,暂停线程之后,出现了数据不同步问题。

0 0