Thread.activeCount()的用法

2018-11-23  本文已影响78人  G先生_海林

此方法返回活动线程的当前线程的线程组中的数量。

public class AtomicIn {
    static AtomicInteger count = new AtomicInteger(0);

    public static void increment() {
        count.getAndIncrement();// 先返回在++
        System.err.println(Thread.currentThread().getName() + "--" + count + "-----");

    }
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            Thread t = new Thread(new Th1());
            t.start();
        }
        System.err.println("**********" + Thread.activeCount());
        while (Thread.activeCount() > 1) {
            Thread.yield();
        }
        System.err.println(AtomicIn.count);
    }

}
class Th1 implements Runnable {
    @Override
    public void run() {
        AtomicIn.increment();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

代码运行结果
Thread-0--3-----
Thread-1--3-----
Thread-2--3-----
**********6
Thread-3--4-----
Thread-4--5-----
5

上一篇 下一篇

猜你喜欢

热点阅读