【java】 java 中stop方法终止线程的不良后果

stop()方法属于暴力终止线程的方法,有诸多隐患已经被废弃了。

下面演示的是stop方法会释放锁,造成数据不一致的问题。

package com.xwolf.java.thread;

/**
 * Created by Administrator on 2015/12/29 0029.
 */
public class SynUser {

    private String name="Jack" ;
    private String pwd="12345";

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    synchronized  public void printUser(String name,String pwd){
        this.name=name;
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.pwd=pwd;
    }


}

测试类:

package com.xwolf.java.thread;

/**
 * Created by Administrator on 2015/12/29 0029.
 */
public class StopThreadReleaseLock extends  Thread {

    private SynUser synUser;
    public StopThreadReleaseLock(SynUser user){
        this.synUser=user;
    }

    @Override
    public void run() {
        synUser.printUser("Suse","linux");
    }

    public static void main(String[] args){
        SynUser user = new SynUser();
        StopThreadReleaseLock lock = new StopThreadReleaseLock(user);
        lock.start();
        try {
            Thread.sleep(300);
            lock.stop();
            System.out.println(user.getName()+","+user.getPwd());//Suse,12345
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

可见,控制台输出的并非预期的结果。

在java中终止线程的替换方法是使用interrupt方法和return结束线程.

 

package com.xwolf.java.thread;

/**
 * Created by Administrator on 2015/12/29 0029.
 *
 * 终止线程的方法
 */
public class StopThread extends  Thread {

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {

            System.out.println(i);
            //当前线程是否中断
            if (this.isInterrupted()) {
                System.out.println("当前线程停止了," + i);
                return;
            }
        }
    }

    public static  void main(String[] args){
        StopThread stopThread = new StopThread();
        stopThread.start();
        stopThread.interrupt();

    }
}

 

posted @ 2015-12-29 16:18  snow__wolf  阅读(1342)  评论(0编辑  收藏  举报