非公平锁

package com.freeflying.thread.reentrantlock;

import java.util.concurrent.locks.ReentrantLock;

public class FairAndNoFair {
	public static void main(String[] args) {
		final FairAndNoFairEx fEx=new FairAndNoFairEx(false);
		Runnable runnable=new Runnable() {
			@Override
			public void run() {
				System.out.println("ThreadA:"+Thread.currentThread().getName()+" is running");
				fEx.method();
			}
		};
		Thread[] threads=new Thread[10];
		for (int i = 0; i < threads.length; i++) {
			threads[i]=new Thread(runnable);
		}
		for (int i = 0; i < threads.length; i++) {
			threads[i].start();
		}
	}
}
class FairAndNoFairEx{
	private ReentrantLock lock;
	public FairAndNoFairEx(boolean isFair) {
		super();
		lock=new ReentrantLock(isFair);
	}
	public void method() {
		try {
			lock.lock();
			System.out.println("ThreadName:"+Thread.currentThread().getName()+"get lock");
		} finally {
			lock.unlock();
		}
	}
}

结果:

ThreadA:Thread-3 is running
ThreadA:Thread-7 is running
ThreadName:Thread-3get lock
ThreadName:Thread-7get lock
ThreadA:Thread-1 is running
ThreadName:Thread-1get lock
ThreadA:Thread-9 is running
ThreadName:Thread-9get lock
ThreadA:Thread-5 is running
ThreadName:Thread-5get lock
ThreadA:Thread-2 is running
ThreadName:Thread-2get lock
ThreadA:Thread-6 is running
ThreadName:Thread-6get lock
ThreadA:Thread-0 is running
ThreadA:Thread-4 is running
ThreadName:Thread-4get lock----这里明显有乱序
ThreadName:Thread-0get lock----
ThreadA:Thread-8 is running
ThreadName:Thread-8get lock

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值