zoukankan      html  css  js  c++  java
  • 多线程wait和notify实现1212

    package threadT;
    
    public class ThreadMain {
        public static void main(String args[]) {
            final Object obj = new Object();// 以该对象为共享资源
            new Thread(new Thread1to2(1, obj), "小明").start();
            new Thread(new Thread1to2(2, obj), "小王").start();
        }
    }
    package threadT;
    
    public class Thread1to2 implements Runnable {
        private final int number;
        private int count = 10;
        public Object obj;
    
        public Thread1to2(int number, Object obj) {
            this.obj = obj;
            this.number = number;
        }
    
        public void run() {
            synchronized (obj) {
                while (count-- > 0) {
                    try {
                        obj.notify();// 唤醒等待res资源的线程,把锁交给线程(该同步锁执行完毕自动释放锁)
                        System.out.println(Thread.currentThread().getName() + "喊:" + number);
                        if (count > 0)
                            obj.wait();// 释放CPU控制权,释放res的锁,本线程阻塞,等待被唤醒。
                        // 如果结束要释放锁,否则会阻塞进程
                        else if (count == 0)
                            obj.notify();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    有追求,才有动力!

    向每一个软件工程师致敬!

    by wujf

    mail:921252375@qq.com

  • 相关阅读:
    SpringBoot页面访问处理
    体验SpringBoot
    体验SpringBoot
    Scala基础
    修改容器配置使其永久生效
    [徐培成系列实战课程]docker篇
    v1.0.2-2017.04.26
    修改容器的hosts文件
    配置spark集群
    配置docker容器上ssh无密登录
  • 原文地址:https://www.cnblogs.com/wujf/p/9090155.html
Copyright © 2011-2022 走看看