1.stop(已经废弃)
太粗暴,容易产生数据不一致,不建议使用
package com.mashibing.juc.c_001_00_thread_end;
import com.mashibing.util.SleepHelper;
public class T01_Stop {
public static void main(String[] args) {
Thread t = new Thread(() -> {
while (true) {
System.out.println("go on");
SleepHelper.sleepSeconds(1);
}
});
t.start();
SleepHelper.sleepSeconds(5);
t.stop();
}
}
2、suspend,resume(已经废弃)
容易产生死锁,不建议使用
package com.mashibing.juc.c_001_00_thread_end;
import com.mashibing.util.SleepHelper;
public class T02_Suspend_Resume {
public static void main(String[] args) {
Thread t = new Thread(() -> {
while (true) {
System.out.println("go on");
SleepHelper.sleepSeconds(1);
}
});
t.start();
SleepHelper.sleepSeconds(5);
// 打断
t.suspend();
SleepHelper.sleepSeconds(3);
// 继续
t.resume();
}
}
3、volatile变量
package com.mashibing.juc.c_001_00_thread_end;
import com.mashibing.util.SleepHelper;
public class T03_VolatileFlag {
private static volatile boolean running = true;
public static void main(String[] args) {
Thread t = new Thread(() -> {
long i = 0L;
while (running) {
//wait recv accept
i++;
}
System.out.println("end and i = " + i); //4168806262 4163032200
});
t.start();
SleepHelper.sleepSeconds(1);
running = false;
}
}
4、interrupt设置标志位
package com.mashibing.juc.c_001_00_thread_end;
import com.mashibing.util.SleepHelper;
/**
* interrupt是设定标志位
*/
public class T04_Interrupt_and_NormalThread {
public static void main(String[] args) {
Thread t = new Thread(() -> {
while (!Thread.interrupted()) {
//sleep wait
}
System.out.println("t1 end!");
});
t.start();
SleepHelper.sleepSeconds(1);
t.interrupt();
}
}
线程安全:废弃方法与正确实践
本文探讨了Java中已废弃的线程控制方法,如stop、suspend和resume,以及它们可能导致的数据不一致和死锁问题。然后介绍了使用volatile变量和interrupt标志位来安全地停止线程的方法,并强调了让线程自然结束的重要性。
1306

被折叠的 条评论
为什么被折叠?



