synchronized和reentrantLock实现两线程交替执行

92 阅读1分钟

一. synchronized通过wait()和notify方法可以控制线程交替执行

public class SychronziedTest {

    public synchronized void test1() throws InterruptedException {
        while (true) {
            System.out.println(Thread.currentThread().getName() + " 开始生产 ");
            notify();
            wait();
        }
    }

    public synchronized void test2() throws InterruptedException {
        while (true) {
            System.out.println(Thread.currentThread().getName() + " 开始消费 ");
            notify();
            wait();
        }
    }

    public static void main(String[] args) {
        SychronziedTest sychronziedTest = new SychronziedTest();

        new Thread(() -> {
            try {
                sychronziedTest.test1();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "thread1").start();

        new Thread(() -> {
            try {
                sychronziedTest.test2();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "thread2").start();
    }

}

结果

thread1 开始生产 
thread2 开始消费 
thread1 开始生产 
thread2 开始消费 
thread1 开始生产 
thread2 开始消费 
......

二. ReentrantLock的condition中的await()和singal()方法可以控制线程交替执行

package com.wade;

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

public class ReentrantLockTest {
    ReentrantLock lock =  new ReentrantLock();
    Condition condition = lock.newCondition();

    public void test1() throws InterruptedException {
        lock.lock();
        try {
            while (true) {
                System.out.println(Thread.currentThread().getName() + " 开始生产 ");
                condition.signal();
                condition.await();
            }
        } finally {
            lock.unlock();
        }
    }

    public void test2() throws InterruptedException {
        lock.lock();
        try {
            while (true) {
                System.out.println(Thread.currentThread().getName() + " 开始消费 ");
                condition.signal();
                condition.await();
            }
        } finally {
            lock.unlock();
        }

    }

    public static void main(String[] args) {
        SychronziedTest sychronziedTest = new SychronziedTest();

        new Thread(() -> {
            try {
                sychronziedTest.test1();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "thread1").start();

        new Thread(() -> {
            try {
                sychronziedTest.test2();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "thread2").start();
    }

}

执行结果:

thread1 开始生产 
thread2 开始消费 
thread1 开始生产 
thread2 开始消费 
thread1 开始生产 
thread2 开始消费 
......