spring 事务之 UserTransaction

UserTransaction

Posted by lijian on April 10, 2019

信号量限流

        //限制3个同时执行线程
        Semaphore semaphore = new Semaphore(3);
        //模拟多线程
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    //尝试获取信号量
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + ":开始执行");
                    //业务操作-休眠2秒
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println(Thread.currentThread().getName() + ":执行完成");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                    System.out.println(Thread.currentThread().getName() + ":----------释放");
                    
                }

            }).start();
        }

RateLimiter 限流


        RateLimiter rateLimiter = RateLimiter.create(3D);
        List<Thread> tasks = new ArrayList<>(20);
        for (int i = 0; i < 20; i++) {
            int finalI1 = i;
            tasks.add(new Thread(() -> {
                System.out.println(finalI1 + " is running");
            }));
        }
        for (Thread item : tasks) {
//            if (rateLimiter.tryAcquire(1,TimeUnit.SECONDS)) {
//                item.start();
//            }
            double waitTime = rateLimiter.acquire();
            System.out.println(waitTime);
            item.start();
        }