ReentrantLock实现线程交替打印

类似同步锁synchronized、wait和notifyAll 线程的等待和唤醒。
实现代码如下:

  • MyService
 `package com.dairuijie.lock.print;

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

/**
 * 
 * @ClassName: MyLockService
 * @Description:TODO()
 * @author: drj
 * @date: 2019年7月28日 下午6:26:44
 * 
 * @Copyright: 2019
 *  */
public class MyLockService {
	public ReentrantLock lock = new ReentrantLock();
	public Condition con = lock.newCondition();

	private boolean hasValue = false;

	public void set() {
		try {
			lock.lock();
			OutInfo();
			while (hasValue) {
				System.out.println(Thread.currentThread().getName() + hasValue);
				con.await();
			}
			System.out.println(Thread.currentThread().getName()+ "set()=========");
			hasValue = true;
			con.signalAll();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}

	public void get() {
		try {
			lock.lock();
			OutInfo();
			while (!hasValue) {
				System.out.println(Thread.currentThread().getName() + hasValue);
				con.await();
			}
			hasValue = false;
			System.out.println(Thread.currentThread().getName() + "get()=======");
			con.signalAll();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}
	
	public void OutInfo() {
		System.out.println("当前线程保持此锁定的个数" + lock.getHoldCount());
		System.out.println("正在等待获取此锁的估计个数" + lock.getQueueLength());
		//System.out.println("正在等待Condition的个数" + lock.getWaitQueueLength(con));
	}
}
  • 线程A
package com.dairuijie.lock.print;

public class MyThread extends Thread {

	private MyLockService lock;

	@Override
	public void run() {
		// TODO Auto-generated method stub
		super.run();
			lock.set();
	}

	public MyThread(MyLockService lock) {
		super();
		this.lock = lock;
	}

}

  • 线程B
 package com.dairuijie.lock.print;

public class MyThreadB extends Thread {

	private MyLockService lock;

	@Override
	public void run() {
		// TODO Auto-generated method stub
		super.run();
		lock.get();
	}

	public MyThreadB(MyLockService lock) {
		super();
		this.lock = lock;
	}

}

  • Main
package com.dairuijie.lock.print;

public class Demo {
	public static void main(String[] args) throws InterruptedException {
		MyLockService lock = new MyLockService();
		for (int i = 0; i < 2; i++) {
			MyThread a = new MyThread(lock);
			a.setName("thread A"  );
			MyThreadB b = new MyThreadB(lock);
			b.setName("thread B" );
			a.start();
			b.start();
		}
	}
}

  • 测试
    当前线程保持此锁定的个数1
    正在等待获取此锁的估计个数3
    thread Aset()=========
    当前线程保持此锁定的个数1
    正在等待获取此锁的估计个数2
    thread Bget()=======
    当前线程保持此锁定的个数1
    正在等待获取此锁的估计个数1
    thread Aset()=========
    当前线程保持此锁定的个数1
    正在等待获取此锁的估计个数0
    thread Bget()=======

你可能感兴趣的:(多线程)