Home
  • 计算机网络
  • 操作系统
  • 数据结构与算法
  • 设计模式
  • JavaSE
  • JVM
  • JUC
  • Netty
  • CPP
  • QT
  • UE
  • Go
  • Gin
  • Gorm
  • HTML
  • CSS
  • JavaScript
  • vue2
  • TypeScript
  • vue3
  • react
  • Spring
  • SpringMVC
  • Mybatis
  • SpringBoot
  • SpringSecurity
  • SpringCloud
  • Mysql
  • Redis
  • 消息中间件
  • RPC
  • 分布式锁
  • 分布式事务
  • 个人博客
  • 弹幕视频平台
  • API网关
  • 售票系统
  • 消息推送平台
  • SaaS短链接系统
  • Linux
  • Docker
  • Git
GitHub (opens new window)
Home
  • 计算机网络
  • 操作系统
  • 数据结构与算法
  • 设计模式
  • JavaSE
  • JVM
  • JUC
  • Netty
  • CPP
  • QT
  • UE
  • Go
  • Gin
  • Gorm
  • HTML
  • CSS
  • JavaScript
  • vue2
  • TypeScript
  • vue3
  • react
  • Spring
  • SpringMVC
  • Mybatis
  • SpringBoot
  • SpringSecurity
  • SpringCloud
  • Mysql
  • Redis
  • 消息中间件
  • RPC
  • 分布式锁
  • 分布式事务
  • 个人博客
  • 弹幕视频平台
  • API网关
  • 售票系统
  • 消息推送平台
  • SaaS短链接系统
  • Linux
  • Docker
  • Git
GitHub (opens new window)
  • 线程

  • 共享模型

    • 管程
    • JMM
    • 乐观锁
    • 线程池
    • J.U,C
    • 异步编程
    • 多线程编程
      • 两个线程交叉打印1-100
      • 循环打印ABC
        • volatile实现
        • ReentrantLock实现
        • Semaphore实现
      • 多线程任务调度
    • 动态线程池
  • 非共享模型

  • 并行

  • 多线程设计模式

  • JUC
  • 共享模型
Nreal
2023-11-23
目录

多线程编程

# 两个线程交叉打印1-100

public class printOneToHundred {
    private static volatile boolean state = true;
    private static volatile int count = 1;
    private static final Object lock = new Object();

    class Producer1 extends Thread {
        @Override
        public void run() {
            while (count < 100) {
                synchronized (lock) {
                    while (!state) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("线程1打印:" + count);
                    count++;
                    state = false;
                    lock.notify();
                    try {
                        Thread.sleep(5);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    class Producer2 extends Thread {
        @Override
        public void run() {
            while (count < 100) {
                synchronized (lock) {
                    while (state) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("线程2打印:" + count);
                    count++;
                    state = true;
                    lock.notify();
                    try {
                        Thread.sleep(5);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        printOneToHundred print = new printOneToHundred();
        Producer1 p = print.new Producer1();
        Producer2 c = print.new Producer2();
        p.start();
        c.start();
    }
}
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

# 循环打印ABC

# volatile实现

public class VolatileOrderThread {

    static volatile int ticket = 1;

    public static void main(String[] args) {

        Thread thread1 = new Thread(() -> {
            while (true) {
                if (ticket == 1) {
                    System.out.println("A");
                    ticket = 2;
                }
            }
        });

        Thread thread2 = new Thread(() -> {
            while (true) {
                if (ticket == 2) {
                    System.out.println("B");
                    ticket = 3;
                }
            }
        });

        Thread thread3 = new Thread(() -> {
            while (true) {
                if (ticket == 3) {
                    System.out.println("C");
                    ticket = 1;
                }
            }
        });

        thread1.start();
        thread2.start();
        thread3.start();
    }
}
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

# ReentrantLock实现

public class PrintABC {
    // 共享变量,表示当前应该打印哪个字母
    private static int state = 0;
    private static ReentrantLock lock = new ReentrantLock();
    private static final Condition A = lock.newCondition();
    private static final Condition B = lock.newCondition();
    private static final Condition C = lock.newCondition();

    public static void main(String[] args) {
        Thread threadA = new Thread(()->{
            try {
                for(int i=0;i<100;i++){
                    lock.lock();
                    try {
                        while(state%3!=0)
                            A.await();
                        System.out.println("A");
                        state++; // 状态修改
                        B.signal();// 唤醒下一个线程
                    } finally {
                        lock.unlock();
                    }
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        Thread threadB = new Thread(()->{
            try {
                for(int i=0;i<100;i++){
                    lock.lock();
                    try {
                        while(state%3!=1)
                            B.await();
                        System.out.println("B");
                        state++; // 状态修改
                        C.signal();// 唤醒下一个线程
                    } finally {
                        lock.unlock();
                    }
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        Thread threadC = new Thread(()->{
            try {
                for(int i=0;i<100;i++){
                    lock.lock();
                    try {
                        while(state%3!=2)
                            C.await();
                        System.out.println("C");
                        state++; // 状态修改
                        A.signal();// 唤醒下一个线程
                    } finally {
                        lock.unlock();
                    }
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        threadA.start();
        threadB.start();
        threadC.start();
    }

}
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

# Semaphore实现

public class PrintABC2 {
    // 三个信号量对象,分别表示A、B、C三个线程的初始许可数
    private static Semaphore A = new Semaphore(1);
    private static Semaphore B = new Semaphore(0);
    private static Semaphore C = new Semaphore(0);

    public static void main(String[] args) {
        Thread threadA = new Thread(()->{
            try {
                for(int i=0;i<100;i++){
                    A.acquire();
                    System.out.println("A");
                    B.release();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        Thread threadB = new Thread(()->{
            try {
                for(int i=0;i<100;i++){
                    B.acquire();
                    System.out.println("B");
                    C.release();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        Thread threadC = new Thread(()->{
            try {
                for(int i=0;i<100;i++){
                    C.acquire();
                    System.out.println("C");
                    A.release();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        threadA.start();
        threadB.start();
        threadC.start();
    }
}
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

# 多线程任务调度

优先级队列+Runnable;

public class Task implements Comparable<Task> {

    private int priority;
    private Runnable runnable;

    public Task(int priority, Runnable runnable) {
        this.priority = priority;
        this.runnable = runnable;
    }

    public void run() {
        runnable.run();
    }

    @Override
    public int compareTo(Task o) {
        return Integer.compare(priority, o.priority);
    }

}

public class MyTaskScheduler {

    private PriorityQueue<Task> queue;

    public MyTaskScheduler() {
        queue = new PriorityQueue<>();
    }

    public void schedule(Task task) {
        queue.offer(task);
    }

    public void run() {
        while (!queue.isEmpty()) {
            Task task = queue.poll();
            task.run();
        }
    }

}
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
异步编程
动态线程池

← 异步编程 动态线程池→

Theme by Vdoing | Copyright © 2021-2024
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式