Java编程思想读书笔记--第21章并发

1.基本的线程机制

  定义任务

public class LiftOff implements Runnable{
    protected int countDown = 10;
    private 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.println(status());
            Thread.yield();
        }
    }
}

  使用Thread类驱动任务

public class BasicThreads {
    public static void main(String[] args) {
        Thread t = new Thread(new LiftOff());
        t.start();
        System.out.println("Waiting for LiftOff");
    }
}

  任务执行完之前垃圾回收器不会回收线程对象。

posted @ 2016-12-09 23:02  语陌1988  阅读(254)  评论(0编辑  收藏  举报