《图解Java多线程设计模式》学习笔记

  • 【日】结城浩 著
  • 侯振龙 杨文轩 译
  • 源码地址点击”随书下载“

第1章 Single Threaded Excution 模式 ——通过这座桥的只有一个人

java.util.concurrent.Semaphore (计数信号量)P53

使用场景

确保某个区域”最多只能由N个线程“执行。

注意事项

semaphore的acquire方法和release方法必须成对调用

示例
import java.util.Random;

import java.util.concurrent.Semaphore;

class Log {
    public static void println(String s) {
        System.out.println(Thread.currentThread().getName() + ": " + s);
    }
}

// 资源个数有限
class BoundedResource {
    private final Semaphore semaphore;
    private final int permits;
    private final static Random random = new Random(314159);

    // 构造函数(permits为资源个数)
    public BoundedResource(int permits) {
        this.semaphore = new Semaphore(permits);
        this.permits = permits;
    }

    // 使用资源
    public void use() throws InterruptedException {
        semaphore.acquire();
        try {
            doUse();
        } finally {
            semaphore.release();
        }
    }

    // 实际使用资源(此处仅使用Thread.sleep)
    protected void doUse() throws InterruptedException {
        Log.println("BEGIN: used = " + (permits - semaphore.availablePermits()));
        Thread.sleep(random.nextInt(500));
        Log.println("END:   used = " + (permits - semaphore.availablePermits()));
    }
}

// 使用资源的线程
class UserThread extends Thread {
    private final static Random random = new Random(26535);
    private final BoundedResource resource;

    public UserThread(BoundedResource resource) {
        this.resource = resource;
    }

    public void run() {
        try {
            while (true) {
                resource.use();
                Thread.sleep(random.nextInt(3000));
            }
        } catch (InterruptedException e) {
        }
    }
}

public class Main {
    public static void main(String[] args) {
        // 设置3个资源
        BoundedResource resource = new BoundedResource(3);

        // 10个线程使用资源
        for (int i = 0; i < 10; i++) {
            new UserThread(resource).start();
        }
    }
}

第2章 Immutable模式——想破坏也破坏不了

使用copy-on-write的java.util.concurrent.CopyOnWriteArrayList类 P75

  1. CopyOnWriteArrayList类是采用copy-on-write技术来避免读写冲突的。
  2. copy-on-write,就是”写时复制“的意思。如果使用copy-on-write,但对集合执行”写“操作时,内部已确保安全的数组就会被整体复制。复制之后,就无需在使用迭代器依次读取元素时担心元素会被修改了。
  3. 使用copy-on-write时,每次执行”写“操作都会执行复制。因此如果写操作比较少,而读操作频率非常高时,使用时非常棒的。

第3章 Guarded Suspension模式——等我准备好哦

使用java.util.concurrent.LinkedBlockingQueue P93

第5章 Producer——Consumer模式

第10章 Two-Phase Termination 模式——先收拾房间再睡觉

java.util.concurrent.CountDownLatch

  • 当我们想让某个线程等待指定的线程终止时使用

java.util.concurrent.CyclicBarrier

  • 当想多次重复进行线程同步时使用
  • 可以周期性的创建出屏障,在屏障解除之前,碰到屏障的线程无法继续前行
  • 可处理分阶段的任务
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值