1 package reentrantlock; 2 3 import java.util.ArrayList; 4 import java.util.concurrent.locks.ReentrantLock; 5 6 public class TestFairSyn { 7 8 public static void main(String[] args) { 9 ArrayList<Thread> arrayList = new ArrayList<>(); 10 Resrc resrc = new Resrc(); 11 12 for (int i = 0; i < 15; i++){ 13 arrayList.add(new Thread(resrc)); 14 } 15 for (int i = 0; i < 15; i++){ 16 arrayList.get(i).start(); 17 } 18 } 19 20 static class Resrc implements Runnable{ 21 private static boolean isTestFair = true; 22 ReentrantLock reentrantLock = new ReentrantLock(isTestFair); 23 24 @Override 25 public void run() { 26 System.out.println(Thread.currentThread().getId()+" 尝试获得锁"); 27 reentrantLock.lock(); 28 if (false){ 29 System.out.println("\t\t" + Thread.currentThread().getId() + " 成功获得锁-解锁"); 30 reentrantLock.unlock(); 31 } 32 else { 33 try { 34 System.out.println("\t\t" + Thread.currentThread().getId() + " 成功获得锁"); 35 // 如果测试 公平锁,把睡眠时间取消,能够大大增加线程的抢占现象 36 Thread.sleep(0, 100); 37 } catch (InterruptedException e) { 38 e.printStackTrace(); 39 } finally { 40 System.out.println("\t\t" + "\t\t" + Thread.currentThread().getId() + " 解锁"); 41 reentrantLock.unlock(); 42 } 43 } 44 } 45 } 46 47 }
原文地址:https://www.cnblogs.com/cnblogszs/p/10361387.html
时间: 2024-11-14 13:04:04