线程的公平锁

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(true);
		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-0 is running
ThreadA:Thread-2 is running
ThreadA:Thread-4 is running
ThreadA:Thread-7 is running
ThreadA:Thread-5 is running
ThreadA:Thread-1 is running
ThreadName:Thread-0get lock
ThreadA:Thread-3 is running
ThreadName:Thread-2get lock
ThreadA:Thread-8 is running
ThreadA:Thread-9 is running
ThreadName:Thread-4get lock
ThreadA:Thread-6 is running
ThreadName:Thread-7get lock
ThreadName:Thread-5get lock
ThreadName:Thread-1get lock
ThreadName:Thread-3get lock
ThreadName:Thread-8get lock
ThreadName:Thread-9get lock
ThreadName:Thread-6get lock

 

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