JAVA多线程终止线程、退出线程、Interrupt()方法、苦逼的搬砖工
方式一: 设置标志位退出
public class Interrupt1 { public static void main(String[] args) throws InterruptedException { SayHello sayHello = new SayHello(); Thread t = new Thread(sayHello); t.start(); //主线程睡5秒后 Thread.sleep(2000); // 停止子线程 sayHello.flag = false; System.out.println("线程退出!"); } } class SayHello implements Runnable{ boolean flag = true ; public void run() { while(flag) { System.out.println("HEllo!"); } } }
方式二:Interrupt()打断退出
public class Interrupt2 { public static void main(String[] args) throws InterruptedException { SayHello2 sayHello = new SayHello2(); Thread t = new Thread(sayHello); t.start(); //主线程睡5秒后 Thread.sleep(5000); //打断子线程的睡眠叫起来干活 t.interrupt(); System.out.println("起来干活!"); } } class SayHello2 implements Runnable{ public void run() { try { Thread.sleep(1000000000L); } catch (InterruptedException e) { System.out.println("老板我马上就起来>>>>>>>>>>>>>>>>>>>>>>>>>"); } for (int i =1; i <=10; i++) { System.out.println("老板我在搬第: "+ i +"堆砖......."); } System.out.println("搬砖真苦B.................!!!!!!!!!!!!!!!!!!"); } }
传播知识,分享快乐!
作者:IT_BULL
出处:http://www.cnblogs.com/itBulls/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
博客园-博客园。