模擬併發及生成唯一

王小胖醬發表於2019-01-17

一、生成唯一id

package com.wxx.demo.util;

import java.text.SimpleDateFormat;

/**
 * @Author : leisure
 * @Date : 2019/1/17
 */
public class IdUtiles {

    private static String lead = "leisure";
    private static int Guid = 100;

    /**
     * 建立以字串打頭結尾自增的唯一id
     * @return
     */
    public static synchronized String creatId(){

        long l = System.currentTimeMillis();

        Guid += 1;

        String format = new SimpleDateFormat("yyyy").format(l);

        if (Guid > 999){
            Guid = 100;
        }

        String id = lead + format + l + Guid;
        return id;
    }
}複製程式碼

二、模擬高併發場景

package com.wxx.demo;

import com.wxx.demo.util.IdUtiles;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.concurrent.CountDownLatch;

@RunWith(SpringRunner.class)
//@SpringBootTest(classes = LeisureWebApplication.class)
public class TaskTest {

    @Test
    public void taskTest(){

        Runnable task = new Runnable() {

            int count = 0;

            @Override
            public void run() {
                count ++;

                String id = IdUtiles.creatId();
                System.out.println(count);
                System.out.println(id);
                System.out.println("Thread : " + Thread.currentThread().getId());

                try {
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }

            }
        };

        double executeTime = this.executeTime(100, task);
        System.out.println("執行時間: " + executeTime);
    }

    private double executeTime(int taskCount,Runnable task){

        CountDownLatch start = new CountDownLatch(1);
        CountDownLatch end = new CountDownLatch(taskCount);

        for (int i = 0; i < taskCount ; i++) {
            Thread thread = new Thread() {

                public void run(){
                    try {
                        start.await();

                        try {
                            task.run();
                        }finally {
                            end.countDown();
                        }

                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
            };

            thread.start();
        }

        long startTime = System.nanoTime();

        //開啟開關
        start.countDown();

        long endTime = System.nanoTime();

        return endTime - startTime;
    }
}
複製程式碼


相關文章