synchronized、wait和notify的实践

简介

synchronized、wait和notify的实践

  • synchronized是对资源进行加锁
  • wait是对让线程进行等待,使线程进行阻塞状态,进入等待队列
  • notify是唤醒等待队列的线程,让其重新进入就绪状态,从而能够竞争时间片,去执行线程

synchronized、notify和wait是需要进行结合使用的,下面这里为使用案例

案例

package ThreadMethod;


public class WaitAndNotifyTest {


    //定义一个资源
    private final static String resource="aa";


    /**
     * 定义线程1
     */
    static class MyRunnbale1 implements Runnable {


        /**
         * 重写run方法
         */
        @Override
        public void run() {
            //加锁
            synchronized (resource){
                System.out.println(Thread.currentThread().getName()+"获取资源");
                try {
                    /**
                     * 调用wait,线程加入等待队列,然后释放锁
                     * 注意wait的使用是 资源对象.wait()  而不是直接使用wait() 不然会报错
                     */
                    System.out.println(Thread.currentThread().getName()+"调用wait,进入等待队列");
                    resource.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(Thread.currentThread().getName()+"重新获得锁");
            }
        }
    }


    /**
     * 定义线程2
     */
    static class MyRunnbale2 implements Runnable{

        @Override
        public void run() {
            /**
             * 加锁,如果获取不到的话会进行等待
             */
            synchronized (resource){
                System.out.println(Thread.currentThread().getName()+"获取资源");
                /**
                 * 通知所有等待队列中的线程,让他们进行就绪状态,等待获取锁
                 */
                resource.notify();
                System.out.println(Thread.currentThread().getName()+"调用notify");
            }

        }
    }



    public static void main(String[] args) throws InterruptedException {

        MyRunnbale1 myRunnbale1 = new MyRunnbale1();
        Thread thread = new Thread(myRunnbale1);

        MyRunnbale2 myRunnbale2 = new MyRunnbale2();
        Thread thread1 = new Thread(myRunnbale2);

        thread.start();
        /**
         * 线程休眠 确保线程0 可以执行wait方法,进入等待队列
         */
        Thread.sleep(300);
        thread1.start();


    }
}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容