微信扫一扫

028-83195727 , 15928970361
business@forhy.com

定义任务(LiftOff)

线程2016-11-02

线程可以驱动任务,因此你需要一种描述任务的方式,这可以由Runnable接口来提供。要想定义任务,只需实现Runnable接口并编写run方法,使得该任务可以执行你的命令。

public class LiftOff implements Runnable {

    protected int countDown = 10;
    private static int taskCount = 0;

    //id可以用来区分任务的多个实例
    private final int id = taskCount++;

    public LiftOff(){
        System.out.println("调用了无参的构造函数");  
    }

    public LiftOff(int countDown){
        this.countDown = countDown;
        System.out.println("调用了有参的构造函数\n"+  
                 "参数内容为:"+countDown);  
    }

    public String status(){

        return "#" + id + "(" + (countDown > 0 ? countDown : "Liftoff!") + "),";

    }

    @Override
    public void run() {

        while(countDown-- > 0){
            System.out.println(status());

            //使当前线程从执行状态(运行状态)变为可执行态(就绪状态)。
            cpu会从众多的可执行态里选择,也就是说,
            当前也就是刚刚的那个线程还是有可能会被再次执行到的,
            并不是说一定会执行其他线程而该线程在下一次中不会执行到了。
            Thread.yield();
        }

    }

    public static void main(String[] args) {
        LiftOff test1 = new LiftOff();
        test1.run();
        System.out.println("\n");
        LiftOff test2 = new LiftOff(5);
        test2.run();
    }


}