您的位置:首页 > 编程语言 > Java开发

Java让线程停止的方法

2017-04-06 10:30 253 查看
好久没写blog了,这段时间没怎么学习有一点点荒废,最近心血来潮,想要重新开写博客,当做自己的成长日记和技术笔记吧。。。。。

最近花精力去了解了一下java线程,今天记录一下线程停止的方法。java线程停止大家所熟知的一般有三种:stop、volatile、interrupt,下面我来分别介绍一下它们:

stop:建议不要用,会让线程戛然而止,无法得知线程完成了什么、没完成什么,当线程正在进行一些耗时操作如读写、数据库操作,突然终止很可能会有错误发生

interrupt:建议不要用,当线程进入阻塞如 Thread.sleep(5000);调用interrupt会抛出异常,而且线程不会停止

错误案例:

class TestThread extends Thread {

private int count = 0;

public void run() {
while(!this.isInterrupted()){

System.out.print("\n TestThread " + count++);

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

public class Main {

public static void main(String args[]){

Thread thread = new TestThread();
thread.start();

try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print("\n parpare to interrupt the thread ");
thread.interrupt();

}
}
运行结果:抛出了异常,而且线程未停止

TestThread 0
TestThread 1
TestThread 2
parpare to interrupt the thread java.lang.InterruptedException: sleep interrupted

TestThread 3	at java.lang.Thread.sleep(Native Method)
at TestThread.run(Main.java:11)

TestThread 4
TestThread 5
TestThread 6
TestThread 7


volatile:建议使用,线程会执行完当前操作后停止。

正确案例1:

class TestRunnable implements Runnable{

volatile boolean isRunning = true;
int count = 0;
public void run() {
while(isRunning){

System.out.print("\n RunThread "+ count++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

}

public class Main {

public static void main(String args[]){

TestRunnable run = new TestRunnable();
Thread thread = new Thread(run,"runnable");
thread.start();

try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print("\n parpare to stop the thread ");
run.isRunning = false;

}
}


运行结果:

RunThread 0
RunThread 1
RunThread 2
RunThread 3
RunThread 4
RunThread 5
parpare to stop the thread


正确案例(2):

class TestThread extends Thread {

private int count = 0;
volatile boolean isRunning = true;

public void run() {
while(isRunning){

System.out.print("\n TestThread " + count++);

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class Main {

public static void main(String args[]){

TestThread tt = new TestThread();
tt.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print("\n parpare to stop the thread ");
tt.isRunning = false;

}
}
运行结果:

TestThread 0
TestThread 1
TestThread 2
TestThread 3
TestThread 4
TestThread 5
parpare to stop the thread


好了,差不多就是这些了,大家有什么问题、建议可以留言。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: