java 使用 sleep + interrupt 实现互斥锁效果

5 篇文章 0 订阅
3 篇文章 0 订阅
import java.util.*;
import java.util.concurrent.CountDownLatch;
 
public class Test {

    private static int threadCount = 300;
    private static int eachLoopTime = 100;
    private static int testTime = 10;
    private static int NOT_GOT_LOCK = 0; // 未占用临界区
    private static int GOT_LOCK = 1; // 已经占用临界区
    private static int IS_DEAD = 2; // 已经死亡
    private static  List<Integer> aliveThreadIndexList = new ArrayList<Integer>();
    private static List<Thread> threadList = new ArrayList<Thread>();
    private static Map<String,String> map  = new HashMap<String, String>(  );
    private static int[] flags = new int[ threadCount ];
    private static Random random = new Random();

    public static void main(String[] args) throws InterruptedException {
        for(int i=0;i<testTime;i++){
            Test.testMyLock();
            Test.testSynchronized();
            System.out.println();
        }
    }


    public static void testMyLock(  ) throws InterruptedException {
        for( int i = 0; i < Test.threadCount; i++ ){
            Test.aliveThreadIndexList.add( i );
            if( i == 0 ){
                Test.flags[ i ] = Test.GOT_LOCK;
            }else{
                Test.flags[ i ] = Test.NOT_GOT_LOCK;
            }
        }

        final CountDownLatch latch = new CountDownLatch( Test.threadCount );
        long t = System.currentTimeMillis();
        for( int i = 0; i < Test.threadCount; i++ ){
            final int currThreadIndex = i;
            Thread thread = new Thread( new Runnable( ) {
                public void run() {
                    for ( int j = 0; j < Test.eachLoopTime; j++ ) {
                        String key = UUID.randomUUID().toString();
                        while ( Test.flags[ currThreadIndex ] == Test.NOT_GOT_LOCK ) {
                            try {
                               Thread.sleep( 3600 * 1000 );
                            } catch (InterruptedException e) {
                               // System.out.println("xxxxxxxxx");
                            }
                        }
                        Test.map.put( key, key );
                        if ( j == ( Test.eachLoopTime - 1 ) ) {
                            Test.flags[ currThreadIndex ] = Test.IS_DEAD;
                            // 如果当前线程已经死亡,将当前线程的角标从 存活线程角标集合中删除( ps: 当前已经进入至临界区,所以 对集合 aliveThreadIndexList 的操作不存在多线程安全问题 )
                           // Test.aliveThreadIndexList.remove( currThreadIndex ); dead loop ,why ????
                            Iterator<Integer> iterator = Test.aliveThreadIndexList.iterator();
                            while( iterator.hasNext() ){
                                if( currThreadIndex  == iterator.next() ){
                                    iterator.remove();
                                }
                            }
                        } else {
                            Test.flags[ currThreadIndex ] = Test.NOT_GOT_LOCK;
                        }
                        // 随机选择一个存活的线程的角标,将临界资源的进入权交给该线程
                        int nextThreadIndex = Test.selectNextThreadIndex();
                        if ( nextThreadIndex > -1 ) {
                            Test.flags[ nextThreadIndex ] = Test.GOT_LOCK;
                            Test.threadList.get( nextThreadIndex ).interrupt();
                        }
                    }
                    latch.countDown();
                }
            });
            Test.threadList.add( thread );
        }
        for( int i = 0; i < Test.threadCount; i++ ){
            Test.threadList.get( i ).start();
        }
        latch.await();
        System.out.println( Test.map.size() );
        System.out.println( "mylock 耗时: " + ( System.currentTimeMillis() - t ) + " 毫秒!" );

        Test.aliveThreadIndexList.clear();
        Test.threadList.clear();
        Test.map.clear();
    }
 
    /**
     * 选择一个随机的线程角标
     * @return
     */
    public static int selectNextThreadIndex(  ){
        // 如果当前不存在存活的线程,则返回 -1
        int size = Test.aliveThreadIndexList.size();
        if( size == 0 ){
            return -1;
        }
        // 否则随机返回一个存活的线程的角标
        return Test.aliveThreadIndexList.get( Test.random.nextInt( size ) );
    }

    public static void testSynchronized(  ) throws InterruptedException {
        final CountDownLatch latch = new CountDownLatch( Test.threadCount );
        long t = System.currentTimeMillis();
        for( int i = 0; i < Test.threadCount; i++ ){
            final int currThreadIndex = i;
            Thread thread = new Thread( new Runnable( ) {
                public void run() {
                    for ( int j = 0; j < Test.eachLoopTime; j++ ) {
                        String key = UUID.randomUUID().toString();
                        synchronized (Test.class){
                            Test.map.put( key, key );
                        }
                    }
                    latch.countDown();
                }
            });
            thread.start();
        }
        latch.await();
        System.out.println( Test.map.size() );
        System.out.println( "testSynchronized 耗时: " + ( System.currentTimeMillis() - t ) + " 毫秒!" );
        Test.map.clear();
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值