二、java多线程编程核心技术之(笔记)——如何停止线程?

时间:2023-03-09 22:16:08
二、java多线程编程核心技术之(笔记)——如何停止线程?

1、异常法

public class MyThread extends Thread {
@Override
public void run() {
super.run();
try {
for (int i = 0; i < 5000000; i++) {
if(this.interrupted()){
System.out.println("我要停止了。。。。。");
throw new InterruptedException(); \\抛出异常
}
System.out.println("i="+(i+1));
}
System.out.println("我在for下边。。");
} catch (InterruptedException e) {
System.out.println(" in MyThread catch..");
e.printStackTrace();
}
} public static void main(String[] args) {
try {
MyThread myThread=new MyThread();
myThread.start();
Thread.sleep(2000);
myThread.interrupt();
} catch (InterruptedException e) {
System.out.println("main catch");
e.printStackTrace();
}
System.out.println("end");
}
}

结果:

二、java多线程编程核心技术之(笔记)——如何停止线程?

2,在沉睡中停止,即在sleep()状态下停止。

public class MyThread extends Thread {
@Override
public void run() {
super.run();
try {
System.out.println("run begin");
Thread.sleep(200000);
System.out.println("run end");
} catch (InterruptedException e) {
System.out.println("在沉睡中被停止!进入catch!"+this.isInterrupted());
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
MyThread thread = new MyThread();
thread.start();
Thread.sleep(200);
thread.interrupt();
} catch (InterruptedException e) {
System.out.println("main catch");
e.printStackTrace();
}
System.out.println("end!");
}
}

结果:

二、java多线程编程核心技术之(笔记)——如何停止线程?

3、暴力停止 stop()(已作废方法,不推荐使用)

注意:

(1)、暴力停止,可能导致清理工作完成不了。

(2)、导致数据的不到同步处理,导致数据不一致问题。

public class MyThread extends Thread {
private int i = 0; @Override
public void run() {
try {
while (true) {
i++;
System.out.println("i=" + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
MyThread thread = new MyThread();
thread.start();
Thread.sleep(8000);
thread.stop();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }

二、java多线程编程核心技术之(笔记)——如何停止线程?

4、使用ruturn停止线程

public class MyThread extends Thread {

    @Override
public void run() {
while (true) {
if (this.isInterrupted()) {
System.out.println("停止了!");
return;
}
System.out.println("timer=" + System.currentTimeMillis());
}
}
public static void main(String[] args) throws InterruptedException {
MyThread t=new MyThread();
t.start();
Thread.sleep(2000);
t.interrupt();
}
}

结果:

二、java多线程编程核心技术之(笔记)——如何停止线程?

二、

(1)suspend 与 resume 的优缺点:

缺点:(1)独占——使用不当,极易造成公共的同步对象的独占,是其他线程无法访问公共的同步对象。

(2) 不同步——因为线程的暂停而导致数据不同步的情况。

(2)、yield() 方法 :放弃当前CPU资源,让其他的任务去占用CPU资源。放弃时间不确定,可能刚刚放弃,马上又获得了CPU时间片。