首页 > 编程语言 > 详细

多线程wait和notify实现1212

时间:2018-05-25 20:54:57      阅读:223      评论:0      收藏:0      [点我收藏+]
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();
                }
            }
        }
    }
}

 

多线程wait和notify实现1212

原文:https://www.cnblogs.com/wujf/p/9090155.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!