[Java] 编程思想 - 并发

avatarplhDigital nomad

定义任务

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

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

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

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

后台线程

public class SimpleDaemons implements Runnable {
    public void run() {
        try {
            while (true) {
                Thread.sleep(100);
                System.out.println(Thread.currentThread() + " " + this);
            }
        } catch (InterruptedException e) {
            System.out.println("sleep() interrupted");
        }
    }

    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 10; i++) {
            Thread daemon = new Thread(new SimpleDaemons());
            daemon.setDaemon(true); // Must call before start() 调用这个才能启动后台进程
            daemon.start();
        }
        System.out.println("All daemons started");
        Thread.sleep(175);
    }
}

输出结果如下

All daemons started
Thread[#30,Thread-2,5,main] SimpleDaemons@4920a538
Thread[#31,Thread-3,5,main] SimpleDaemons@1a74797c
Thread[#37,Thread-9,5,main] SimpleDaemons@2402a357
Thread[#28,Thread-0,5,main] SimpleDaemons@27ccf550
Thread[#34,Thread-6,5,main] SimpleDaemons@329803a8
Thread[#32,Thread-4,5,main] SimpleDaemons@c1a93d0
Thread[#29,Thread-1,5,main] SimpleDaemons@192d97c8
Thread[#33,Thread-5,5,main] SimpleDaemons@6da3ae10
Thread[#35,Thread-7,5,main] SimpleDaemons@166341a8
Thread[#36,Thread-8,5,main] SimpleDaemons@4cf8dbb0