人生最可悲的事情,莫过于胸怀大志,却又虚度光阴。 ​​​​

《Thinking In Java》读书笔记 第21章 并发

2014.12.24

21.1 并发的多面性

21.1.1 更快的执行

21.1.2 改进代码设计

21.2 基本的线程机制

21.2.1 定义任务

public class LiftOff implements Runnable {
    protected int countDown = 10;
    public static int taskCount = 0;
    private final int id = taskCount++;

    public LiftOff() {
    }

    public LiftOff(int countDown) {
        this.countDown = countDown;
    }

    public String status() {
        return "#" + id + "(" + (countDown > 0 ? countDown : "Liftoff!") + "). ";
    }

    @Override
    public void run() {
        while (countDown-- > 0) {
            System.out.print(status());
            Thread.yield();
        }
    }
}
public class MainThread {
    public static void main(String[] args) {
        LiftOff launch = new LiftOff();
        launch.run();
    }
}

21.2.2 Thread类

public class BasicThreads {
    public static void main(String[] args) {
        Thread t = new Thread(new LiftOff());
        t.start();
        System.out.println("Waiting for LiftOff");
    }
}
/*
输出
Waiting for LiftOff
#0(9). #0(8). #0(7). #0(6). #0(5). #0(4). #0(3). #0(2). #0(1). #0(Liftoff!).
 */

21.2.3 使用Executor

public class CachedThreadPool {
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++) {
            exec.execute(new LiftOff());
        }
        exec.shutdown();
    }
}

21.2.4 从任务中产生返回值

class TaskWithResult implements Callable<String> {
    private int id;

    public TaskWithResult(int id) {
        this.id = id;
    }

    public String call() {
        return "result of TaskWithResult " + id;
    }
}

public class CallableDemo {
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        ArrayList<Future<String>> results = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            results.add(exec.submit(new TaskWithResult(i)));
        }
        for (Future<String> fs : results) {
            try {
                System.out.println(fs.get());
            } catch (InterruptedException e) {
                System.out.println(e);
                return;
            } catch (ExecutionException e) {
                System.out.println(e);

            } finally {
                exec.shutdown();
            }
        }
    }
}

21.2.5 休眠

21.2.6 优先级

21.2.7 让步

21.2.8 后台线程

21.2.9 编码的变体

21.2.10 术语

21.2.11 加入一个线程

21.2.12 创建有响应的用户界面

21.2.13 线程组

21.2.14 捕获异常

21.3 共享受限资源

21.3.1 不正确地访问资源

21.3.2 解决共享资源竞争

21.3.3 原子性与易变性

21.3.4 原子类

21.3.5 临界区

21.3.6 在其他对象上同步

21.3.7 线程本地存储

21.4 终结任务

21.5 线程之间的协作

21.6 死锁

21.7 新类库中的构件

21.8 仿真

21.9 性能调优

21.10 活动对象