WangHan
2024-09-12 d5855a4926926698b740bc6c7ba489de47adb68b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import tech.powerjob.common.utils.SegmentLock;
import org.junit.jupiter.api.Test;
 
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
/**
 * 分段锁测试
 *
 * @author tjq
 * @since 2020/6/15
 */
public class SegmentLockTest {
 
    @Test
    public void testLock() throws Exception {
        int lockId = 10086;
        SegmentLock lock = new SegmentLock(4);
        ExecutorService pool = Executors.newFixedThreadPool(2);
        pool.execute(() -> {
            System.out.println("before lock A");
            lock.lockInterruptibleSafe(lockId);
            System.out.println("after lock A");
        });
 
        pool.execute(() -> {
            System.out.println("before lock AA");
            lock.lockInterruptibleSafe(lockId);
            System.out.println("after lock AA");
        });
 
        Thread.sleep(10000);
    }
 
    @Test
    public void testUnLock() throws Exception {
        int lockId = 10086;
        SegmentLock lock = new SegmentLock(4);
        ExecutorService pool = Executors.newFixedThreadPool(2);
        pool.execute(() -> {
            System.out.println("before lock A");
            lock.lockInterruptibleSafe(lockId);
            System.out.println("after lock A");
            try {
                Thread.sleep(5000);
            }catch (Exception ignore) {
            }
            lock.unlock(lockId);
        });
 
        pool.execute(() -> {
            System.out.println("before lock AA");
            lock.lockInterruptibleSafe(lockId);
            System.out.println("after lock AA");
        });
 
        Thread.sleep(10000);
    }
 
}