美文网首页
Thread.activeCount()的用法

Thread.activeCount()的用法

作者: G先生_海林 | 来源:发表于2018-11-23 16:26 被阅读78次

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

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

相关文章

网友评论

      本文标题:Thread.activeCount()的用法

      本文链接:https://www.haomeiwen.com/subject/mpgjqqtx.html