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.................!!!!!!!!!!!!!!!!!!");
    }    
}

 

posted @ 2018-05-23 11:25  马鞍山  阅读(211)  评论(0编辑  收藏  举报