🚩JUC 经典代码

 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package juc;

import java.util.concurrent.*;

/**
 * 一个线程1,3,5,7;一个线程 2,4,6,8;合作输出 1,2,3,4,5,6,7,8
 * 核心思想:
 * 1. 使用synchronized关键字对lock对象进行同步
 * 2. 使用wait和notify方法实现线程之间的交替输出
 * 3. 输出的数字用 volatile 修饰,保证可见性
 */
public class AlternatePrinting {
    private static final Object lock = new Object();
    private static volatile int count = 1;

    public static void main(String[] args) {
        // 等价于newFixedThreadPool(2),但是阻塞队列上限不是 Integer.MAX_VALUE
        ExecutorService executorService = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(1), new CustomThreadFactory());
        executorService.submit(new OddPrinter());
        executorService.submit(new EvenPrinter());
        executorService.shutdown();
    }

    static class CustomThreadFactory implements ThreadFactory {
        private static final String THREAD_NAME_PREFIX = "MyThread-";
        private int threadCount = 1;

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setName(THREAD_NAME_PREFIX + threadCount++);
            return thread;
        }
    }

    static class OddPrinter implements Runnable {
        @Override
        public void run() {
            while (count <= 8) {
                synchronized (lock) {
                    if (count % 2 != 0) {
                        System.out.println(count++ + " by " + Thread.currentThread().getName());
                        lock.notify();
                    } else {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    static class EvenPrinter implements Runnable {
        @Override
        public void run() {
            while (count <= 8) {
                synchronized (lock) {
                    if (count % 2 == 0) {
                        System.out.println(count++ + " by " + Thread.currentThread().getName());
                        lock.notify();
                    } else {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}

以上代码由 ChatGPT 生成,经验证可以实现功能。

0%