首页 > 代码库 > notify,wait,synchronized实现线程间通知

notify,wait,synchronized实现线程间通知

wait阻塞线程释放锁;notify使wait所在的线程被唤醒在次获得锁,并执行,但要等到notify所在的线程代码全部执行后!

示例代码如下:

package com.vhbi.service.impl;

import com.sun.org.apache.xerces.internal.xs.datatypes.ObjectList;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by zzq on 2017/5/8.
 */
public class TeamTest {

    private LinkedList _list = new LinkedList<Object>();

    private int size = 0;

    private AtomicInteger atomicInteger = new AtomicInteger();

    public TeamTest(int size) {
        this.size = size;
    }

    private final Object lock = new Object();

    public void take() throws Exception {
        synchronized (lock) {
            while (0 == atomicInteger.get()) {//计数器和最大值相等
                lock.wait();//进入等待状态,释放锁
            }
            //被唤醒后
            //1.计数器减一
            atomicInteger.decrementAndGet();
            //2.队列去掉一个
            Object currObj = _list.removeFirst();
            System.out.println("------take------ " + currObj);
            //3.获得锁,唤醒wait执行线程的等待
            lock.notify();
        }
    }

    public void put(Object obj) throws Exception {
        synchronized (lock) {
            while (this.size == atomicInteger.get()) {//计数器和最大值相等
                lock.wait();//进入等待状态,释放锁
            }
            //被唤醒后
            //1.计数器加一
            atomicInteger.incrementAndGet();
            //2.队列添加一个
            _list.add(obj);
            System.out.println("------put------ " + obj);
            //3.获得锁,唤醒wait执行线程的等待
            lock.notify();
        }
    }
}

测试结果代码:

 @org.junit.Test
    public void main2() throws Exception {
        final TeamTest teamTest = new TeamTest(5);
        teamTest.put(1);
        teamTest.put(2);
        teamTest.put(3);
        teamTest.put(4);
        teamTest.put(5);

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    teamTest.put(6);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();

        Thread.sleep(5000);
        teamTest.take();

    }

    @org.junit.Test
    public void main3() throws Exception {
        final TeamTest teamTest = new TeamTest(5);


        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    teamTest.take();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();

        Thread.sleep(5000);
        teamTest.put(1);
        teamTest.put(2);

    }

 

notify,wait,synchronized实现线程间通知