多线程进阶学习07------线程中断与等待唤醒

线程的中断协商机制

什么是中断

一个线程不应该由其他线程来强制中断或停止,而是应该由线程自己自行停止。所以,Thread.stop、Thread.suspend、Thread. resume都已经被废弃了。

在Java中没有办法立即停止一条线程,然而停止线程却显得尤为重要,如取消一个耗时操作。
因此,Java提供了一种用于停止线程的机制即中断。中断只是一种协作机制,Java没有给中断增加任何语法,中断的实现完全需要程序员自己实现。

1、每个线程对象中都有一个标识,用于标识线程是否被中断;该标识位为true表示中断,为false表示未中断;若要中断协商一个线程,你需要手动调用该线程的interrupt方法,该方法也仅仅是
将线程对象的中断标识设为true。
2、interrupt可以在别的线程中调用,也可以在自己的线程中调用

interrupt

线程t1线程t2,当线程t2调用t1.interrupt()时

中断协商:如果t1线程处于正常活动状态,当线程t2调用t1.interrupt()时,那么会将t1线程的中断标志设置为true,仅此而已。t1线程将继续正常运行不受影响

isInterrupted

通过检查中断标志位判断当前线程是否被中断
●若中断标志为true,则isInterrupted返回true
●若中断标志为false,则isInterrupted返回false

静态方法interrupted

判断线程是否被中断,并清除当前中断状态,这个方法做了两件事:
●返回当前线程的中断状态
●将当前线程的中断状态重置即设为false

假设有两个线程A、B,线程B调用了interrupt方法。
后面如果我们连接调用两次interrupted方法,第一次会返回true,然后这个方法会将中断标识位设置位false,
所以第二次调用interrupted将返回false

中断运行中的线程

volatile

static volatile boolean isStop = false;

    public static void main(String[] args) {
        new Thread(() -> {
            while (true) {
                if (isStop) {
                    System.out.println(Thread.currentThread().getName() + "\t isStop被修改为true,程序停止");
                    break;
                }
                System.out.println("t1 -----hello volatile");
            }
        }, "t1").start();

        //暂停毫秒
        try {
            TimeUnit.MILLISECONDS.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            isStop = true;
        }, "t2").start();

    }

AtomicBoolean

static AtomicBoolean atomicBoolean = new AtomicBoolean(false);

    public static void main(String[] args) {
        new Thread(() -> {
            while (true) {
                if (atomicBoolean.get()) {
                    System.out.println(Thread.currentThread().getName() + "\t atomicBoolean被修改为true,程序停止");
                    break;
                }
                System.out.println("t1 -----hello atomicBoolean");
            }
        }, "t1").start();

        //暂停毫秒
        try {
            TimeUnit.MILLISECONDS.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            atomicBoolean.set(true);
        }, "t2").start();

    }

interrupt+isInterrupted

 static volatile boolean isStop = false;

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println(Thread.currentThread().getName() + "\t isInterrupted()被修改为true,程序停止");
                    break;
                }
                System.out.println("t1 -----hello interrupt api");
            }
        }, "t1");
        t1.start();

        System.out.println("-----t1的默认中断标志位:" + t1.isInterrupted());

        //暂停毫秒
        try {
            TimeUnit.MILLISECONDS.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //t2向t1发出协商,将t1的中断标志位设为true希望t1停下来
        new Thread(() -> {
            t1.interrupt();
        }, "t2").start();
        //t1.interrupt();,t1也可以自己给自己协商

    }

等待唤醒

线程等待与唤醒的方式演进:

多线程进阶学习07------线程中断与等待唤醒_第1张图片
LockSupport是用来创建锁和其他同步类的基本线程阻塞原语。LockSupport类使用了一种名为Permit(许可)的概念来做到阻塞和唤醒线程的功能,每个线程都有一个许可(permit),permit只有两个值1和零,默认是零。可以把许可看成是一种(0,1)信号量(Semaphore),但与Semaphore不同的是,许可的累加上限是1

阻塞方法park:

①. permit默认是0,所以一开始调用park()方法,当前线程就会阻塞,直到别的线程将当前线程的permit设置为1时, park方法会被唤醒,然后会将permit再次设置为0并返回
②. static void park( ):底层是unsafe类native方法

唤醒方法unpark:

①. 调用unpark(thread)方法后,就会将thread线程的许可permit设置成1(注意多次调用unpark方法,不会累加,permit值上限是1)会自动唤醒thread线程,即之前阻塞中的LockSupport.park()方法失效
②. static void unpark( ):底层是unsafe类native方法

LockSupport它的解决的痛点:
①. LockSupport不用持有锁块,在代码书写方面不用加锁
②. 唤醒与阻塞的先后顺序,即使先调用唤醒再调用阻塞也不会导致程序卡死报异常,因为unpark获得了一个凭证,之后再调用park方法,就可以名正言顺的依据凭证消费

demo

public class LockSupportDemo {
    static int x = 0;
    static int y = 0;

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "\t ----come in" + System.currentTimeMillis());
            LockSupport.park();
            System.out.println(Thread.currentThread().getName() + "\t ----被唤醒" + System.currentTimeMillis());
        }, "t1");
        t1.start();

        //暂停几秒钟线程
        //try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }

        new Thread(() -> {
            LockSupport.unpark(t1);
            System.out.println(Thread.currentThread().getName() + "\t ----发出通知");
        }, "t2").start();

    }
}

生产者与消费者

synchronized

public class ProductorAndConsumer {
    public static void main(String[] args) {
        Market market = new Market();
        Productor productor = new Productor(market);
        Consumer consumer = new Consumer(market);

        new Thread(productor, "生产者A").start();
        new Thread(consumer, "消费者B").start();
        new Thread(productor, "生产者C").start();
        new Thread(consumer, "消费者D").start();
    }
}

//商店
class Market {

    //某件商品数量,最开始为0
    private int product = 0;

    //进货方法,在多线程环境下,如果不加锁会产生线程安全问题,这里加synchronized锁
    public synchronized void get() {
        //限定商店容量为10
        while (product > 10) {
            System.out.println("仓库已满!");
            //当仓库已满,需要停止生产
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + "进货成功!-->" + ++product);
        //当进货成功,就需要唤醒
        this.notifyAll();
    }

    //出售方法
    public synchronized void sale() {
        while (product <= 0) {
            System.out.println("已售罄!");
            //售罄之后需要停止去生产
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + "出售成功-->" + --product);
        //出售成功之后需要生产
        this.notifyAll();
    }
}

//生产者,生产者不可能只有一个,所以是多线程的
class Productor implements Runnable {
    private Market market;

    public Productor(Market market) {
        this.market = market;
    }

    @Override
    public void run() {
        //一次买15个
        for (int i = 0; i < 15; i++) {
            market.get();
        }
    }
}

//消费者
class Consumer implements Runnable {
    private Market market;

    public Consumer() {
    }

    public Consumer(Market market) {
        this.market = market;
    }

    @Override
    public void run() {
        //一次买10个
        for (int i = 0; i < 10; i++) {
            market.sale();
        }
    }
}

Lock

/*
 * 使用Lock代替Synchronized来实现新版的生产者和消费者模式 !
 * */
@SuppressWarnings("all")
public class ThreadWaitNotifyDemo {
    public static void main(String[] args) {
        AirCondition airCondition = new AirCondition();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) airCondition.decrement();
        }, "线程A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) airCondition.increment();
        }, "线程B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) airCondition.decrement();
        }, "线程C").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) airCondition.increment();
        }, "线程D").start();
    }
}

class AirCondition {
    private int number = 0;
    //定义Lock锁对象
    final Lock lock = new ReentrantLock();
    final Condition condition = lock.newCondition();

    //生产者,如果number=0就 number++
    public void increment() {
        lock.lock();
        try {
            //1.判断
            while (number != 0) {
                try {
                    condition.await();//this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //2.干活
            number++;
            System.out.println(Thread.currentThread().getName() + ":\t" + number);
            //3.唤醒
            condition.signalAll();//this.notifyAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    //消费者,如果number=1,就 number--
    public void decrement() {
        lock.lock();
        try {
            //1.判断
            while (number == 0) {
                try {
                    condition.await();//this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //2.干活
            number--;
            System.out.println(Thread.currentThread().getName() + ":\t" + number);
            //3.唤醒
            condition.signalAll();//this.notifyAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

Lock带顺序的生产者与消费者

/*
    多个线程之间按顺序调用,实现A->B->C
三个线程启动,要求如下:
    AA打印5次,BB打印10次,CC打印15次
    接着
    AA打印5次,BB打印10次,CC打印15次
    ....来10轮
* */
public class ThreadOrderAccess {
    public static void main(String[] args) {
        ShareResource shareResource = new ShareResource();

        new Thread(() -> {
            for (int i = 1; i <= 10; i++) shareResource.print5();
        }, "线程A").start();
        new Thread(() -> {
            for (int i = 1; i <= 10; i++) shareResource.print10();
        }, "线程B").start();
        new Thread(() -> {
            for (int i = 1; i <= 10; i++) shareResource.print15();
        }, "线程C").start();
    }
}

class ShareResource {

    //设置一个标识,如果是number=1,线程A执行...
    private int number = 1;

    Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();


    public void print5() {
        lock.lock();
        try {
            //1.判断
            while (number != 1) {
                condition1.await();
            }
            //2.干活
            for (int i = 1; i <= 5; i++) {
                System.out.println(Thread.currentThread().getName() + ":\t" + i);
            }
            //3.唤醒
            number = 2;
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void print10() {
        lock.lock();
        try {
            //1.判断
            while (number != 2) {
                condition2.await();
            }
            //2.干活
            for (int i = 1; i <= 10; i++) {
                System.out.println(Thread.currentThread().getName() + ":\t" + i);
            }
            //3.唤醒
            number = 3;
            condition3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void print15() {
        lock.lock();
        try {
            //1.判断
            while (number != 3) {
                condition3.await();
            }
            //2.干活
            for (int i = 1; i <= 15; i++) {
                System.out.println(Thread.currentThread().getName() + ":\t" + i);
            }
            //3.唤醒
            number = 1;
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

你可能感兴趣的:(多线程,学习,java,多线程,线程中断,等待唤醒)