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(); } }