Java synchronized关键字

synchronized关键字简化了加锁语句,可以省略Lock.lock()、Lock.unlock()、Condition.await()、Condition.SignalAll()语句,可以与condition对比

/**
 * Created by LvJianwei on 2018/2/11.
 */

import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: ConditionDemo
 * @description:
 * @author: LvJianwei
 * @create: 2018-02-11 15:57
 **/
public class SynchronizedDemo {

    public static void main(String[] args) {
        SynchronizedDemo demo = new SynchronizedDemo();
        Runnable rAdd = () -> {

                try {
                    demo.countAdd();
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

        };
        Runnable rReduce = () -> {

                try {
                    demo.countReduce();
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

        };
        for (int i = 0; i < 5; i++) {
            Thread t = new Thread(rReduce);
            t.start();
        }
        for (int i = 0; i < 5; i++) {
            Thread t = new Thread(rAdd);
            t.start();
        }

    }

    private Random random = new Random(System.currentTimeMillis());
    private ReentrantLock locker = new ReentrantLock();
    private Condition enough;
    private int count = 0;
    private int enoughCount = 3;

    public SynchronizedDemo() {
        enough = locker.newCondition();
    }

    public synchronized void countAdd() {

        count++;
        System.out.printf("Add,count:%d
", count);
        if (count > enoughCount) {
            System.out.println("notifyAll");
            notifyAll();
        }

    }

    public synchronized void countReduce() {
        System.out.println("countReduce start,threadID:" + Thread.currentThread().getId());

        while (count < enoughCount) {
            System.out.printf("threadID:%s,await,count:%d
", Thread.currentThread().getId(), count);
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count--;
        System.out.printf("threadID:%s,reduce,count:%d
", Thread.currentThread().getId(), count);
    }

}

输出:

countReduce start,threadID:12
threadID:12,await,count:0
Add,count:1
Add,count:2
Add,count:3
countReduce start,threadID:15
threadID:15,reduce,count:2
countReduce start,threadID:11
threadID:11,await,count:2
Add,count:3
Add,count:4
notifyAll
countReduce start,threadID:14
threadID:14,reduce,count:3
countReduce start,threadID:13
threadID:13,reduce,count:2
threadID:11,await,count:2
threadID:12,await,count:2
原文地址:https://www.cnblogs.com/lvjianwei/p/8443014.html