线程锁机制

等待/通知机制

线程之间不是独立的的个体,他们彼此之间可以相互通信和协作。

不使用等待、通知机制实现线程间通信

两线程同时调用一个实体对象,即可实现最简单的线程间通信,但是需要以轮询的方式检测某个条件。

等待/通知机制

等待/通知机制可以类比生活中的例子,例如在餐厅就餐。

厨师和服务员之间的交互要在"菜品传递台"上,在这期间会有几个问题:

1. 厨师做完一道菜的时间不确定,所以厨师将菜品放到"菜品传递台"上时间也不确定。

2. 服务员取到菜的时间取决于厨师,所以服务员就有“等待”(wait)状态。

3. 服务员如何能取到菜?这又是取决于厨师,厨师将菜放在“菜品传递台上”,其实就相当于一种通知(notify),这时服务员才可以拿到菜并交给就餐者。

4. 在这个过程中出现“等待/通知”机制。

wait/notify机制

wait()方法的作用是使当前执行的代码线程进行等待,wait()是Object的方法,改方法用来将当前线程至于“预执行队列”中,并且在wait()所在的代码行处停止执行,指导接到通知或者被中断为止。在调用wait()之前,线程必须获得该对象的对象锁,即只能在同步方法或者同步块中调用wait()方法。在执行wait()方法后,当前线程释放锁。在从wait()方法返回前,线程与其他线程竞争重新获得锁。若调用wait()时没有持有适当的锁,则抛出IllegalMonitorStateException,他是RuntimeException的一个子类,因此不需要try/catch语句进行捕捉异常。

方法notify()也要在同步方法或同步块中调用,即在调用前获得对象锁,若无所则一样抛异常。该方法用来通知那些等待该对象的对象锁的其他线程。若有多个线程等待,则由线程规划器随机挑选出其中的一个呈wait状态的线程,对其发出通知notify,并使他获得对象锁。

notify()方法后,当前线程不会马上释放对象锁,呈wait线程也不会立刻获取对象锁,等到执行notify的线程执行完毕后即可释放对象锁,也就是执行完synchronized代码块之后。

若同步块无notify()方法即不会唤醒wait()线程。

java

    public class MyList {

        private static List list = new ArrayList();

        public static void add() {

            list.add("anyString");

        }

        public static int size() {

            return list.size();

        }

    }


    public class ThreadA implements Runnable{

        private Object lock;

        public ThreadA(Object lock) {

            super();

            this.lock = lock;

        }


        @Override

        public void run() {

            try {

                synchronized (lock) {

                    if (MyList.size() != 5) {

                        System.out.println("wait begin " + System.currentTimeMillis());

                        lock.wait();

                        System.out.println("wait end " + System.currentTimeMillis());

                    }

                }


            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

    }

    public class ThreadB implements Runnable {

        private Object lock;

        public ThreadB(Object lock) {

            super();

            this.lock = lock;

        }


        @Override

        public void run() {

            try {

                synchronized (lock) {

                    for (int i = 0; i < 10; i++) {

                        MyList.add();

                        //System.out.println(MyList.size());

                        if (MyList.size() == 5) {

                            lock.notify();

                            System.out.println("已发出通知!");

                        }

                        System.out.println("添加了 " + (i + 1) + " 个元素");

                        Thread.sleep(1000);


                    }

                }

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

    }

    public class Run {

        public static void main(String[] args) {

            try {

                Object lock = new Object();

                ThreadA t1 = new ThreadA(lock);

                Thread thread1 = new Thread(t1);

                thread1.start();

                Thread.sleep(50);

                ThreadB t2 = new ThreadB(lock);

                Thread thread2 = new Thread(t2);

                thread2.start();

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

    }

    /*

    wait begin 1523502226696

    添加了 1 个元素

    添加了 2 个元素

    添加了 3 个元素

    添加了 4 个元素

    已发出通知!

    添加了 5 个元素

    添加了 6 个元素

    添加了 7 个元素

    添加了 8 个元素

    添加了 9 个元素

    添加了 10 个元素

    wait end 1523502236749

    */


本地验证了notify()后不是立刻放弃对象锁,而是等待当前线程执行完成。

notify()只是唤醒一个线程,notifyAll()则是唤醒全部等待线程,按线程优先级依次执行,也可能是随机执行,需要取决于JVM虚拟机的实现。

线程wait状态下如果被interrupt()会被抛异常。

wait(long)的使用

带一个参数的wait(long)方法的功能是等待某一时间内是否有线程对锁进行唤醒,如果超过这个世界就自动唤醒。

通知过早

通知过早就不会唤醒了。

等待wait的条件发生变化

在使用wait/notify模式时,还需要注意wait等待的条件发生了变化,容易造成程序逻辑的混乱。

join方法

join方法的作用是运行所属线程对象x正常执行run()方法,是当前线程在x未结束之前无限阻滞。等待x线程执行完毕后再执行当前线程的后续操作,实现线程间的同步。

join(long)和sleep(long)相比具有释放锁的特点,join(long)的实现实际是使用了wait(long) 方法。

线程嵌套可能会有抢锁的情况,导致join(long)结果不确定。

ThreadLocal类的使用

ThreadLocal解决的是变量在多线程间的隔离性,也就是不同线程拥自己的值

    public class Tools {


        /** Field t1 */

        public static ThreadLocal t1 = new ThreadLocal();

    }



    public class ThreadA extends Thread {

        @Override

        public void run() {

            try {

                for (int i = 0; i < 100; i++) {

                    Tools.t1.set("ThreadA" + (i + 1));

                    System.out.println("ThreadA get Value = " + Tools.t1.get());

                    Thread.sleep(200);

                }

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

    }



    public class ThreadB extends Thread {

        @Override

        public void run() {

            try {

                for (int i = 0; i < 100; i++) {

                    Tools.t1.set("ThreadB" + (i + 1));

                    System.out.println("ThreadB get Value = " + Tools.t1.get());

                    Thread.sleep(200);

                }

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

    }




    public class Run {


        /**

        * Method main

        *

        *

        * @param args

        */

        public static void main(String[] args) {

            try {

                ThreadA a = new ThreadA();

                ThreadB b = new ThreadB();


                a.start();

                b.start();


                for (int i = 0; i < 100; i++) {

                    Tools.t1.set("Main get Value = " + (i + 1));

                    System.out.println("Main get Value = " + Tools.t1.get());

                }


                Thread.sleep(200);

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

    }



    /*result:

    Main get Value = Main get Value = 1

    ThreadB get Value = ThreadB1

    ThreadA get Value = ThreadA1

    Main get Value = Main get Value = 2

    Main get Value = Main get Value = 3

    Main get Value = Main get Value = 4

    ... ...

    */

如上述代码所示,各线程靠ThreadLocal存下了各自的值,互不干扰。

InheritableThreadLocal类的使用

InheritableThreadLocal类的使用可以让子线程取到从父线程中继承下来的值。

    package com.tz3.InheritableThreadLocal1;


    import java.util.Date;


    /**

    * Class InheritableThreadLocalExt

    *

    *

    * @version        1.0, 18/04/21

    * @author        tz

    */

    public class InheritableThreadLocalExt extends InheritableThreadLocal {

        @Override

        protected Object initialValue() {

            return new Date().getTime();

        }

    }



    package com.tz3.InheritableThreadLocal1;


    /**

    * create by tz on 2018-04-21

    */

    public class Tools {

        public static InheritableThreadLocalExt t1 = new InheritableThreadLocalExt();

    }




    package com.tz3.InheritableThreadLocal1;


    /**

    * create by tz on 2018-04-21

    */

    public class ThreadA extends Thread {

        @Override

        public void run() {

            try {

                for (int i = 0; i < 10; i++) {

                    System.out.println("在ThreadA线程中取值 = " + Tools.t1.get());

                    Thread.sleep(100);

                }

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

    }




    package com.tz3.InheritableThreadLocal1;


    /**

    * create by tz on 2018-04-21

    */

    public class Run {


        /**

        * Method main

        *

        *

        * @param args

        */

        public static void main(String[] args) {

            try {

                for (int i = 0; i < 10; i++) {

                    System.out.println("    在main线程中取值 = " + Tools.t1.get());

                    Thread.sleep(100);

                }


                Thread.sleep(5000);


                ThreadA a = new ThreadA();


                a.start();

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

    }





    /*result:

    在main线程中取值 = 1524286163812

        在main线程中取值 = 1524286163812

        在main线程中取值 = 1524286163812

        在main线程中取值 = 1524286163812

        在main线程中取值 = 1524286163812

        在main线程中取值 = 1524286163812

        在main线程中取值 = 1524286163812

        在main线程中取值 = 1524286163812

        在main线程中取值 = 1524286163812

        在main线程中取值 = 1524286163812

    在ThreadA线程中取值 = 1524286163812

    在ThreadA线程中取值 = 1524286163812

    在ThreadA线程中取值 = 1524286163812

    在ThreadA线程中取值 = 1524286163812

    在ThreadA线程中取值 = 1524286163812

    在ThreadA线程中取值 = 1524286163812

    在ThreadA线程中取值 = 1524286163812

    在ThreadA线程中取值 = 1524286163812

    在ThreadA线程中取值 = 1524286163812

    在ThreadA线程中取值 = 1524286163812

    */

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • JAVA面试题 1、作用域public,private,protected,以及不写时的区别答:区别如下:作用域 ...
    JA尐白阅读 4,858评论 1 0
  • ``` /* * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject ...
    非专业码农阅读 2,701评论 0 0
  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 5,808评论 0 9
  • 概述 这篇文章中,我不会说多线程是什么、线程和进程的区别、多线程有什么用,当然我也不会说什么是串行、什么是并行等问...
    hashakey阅读 2,383评论 0 0
  • 在这咋暖还寒的时节里,春回大地,万物复苏,青青的草,娇艳欲滴的花朵争相绽放,无不在向我们宣誓着春的到来! 早春时节...
    芳名阅读 3,514评论 0 0