java - 控制并发线程数

查看:158
本文介绍了java - 控制并发线程数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

public class Test{
   private final Integer maxCounter = 3;
    private Integer current = 0;
    public void call1(){
        //在这里补充代码
    }

    private void call2(Integer current){
        System.out.println("I'm called"+current);
    }

    static class TestThread implements Runnable{
        private Test t;
        public TestThread(Test t){
            this.t = t;
        }
        public void run() {
            t.call1();
        }
    }
    public static void main(String... args){
        Test t1 = new Test();
        TestThread tt = new TestThread(t1);
        for(int i = 0; i < 10; i++){
            Thread t = new Thread(tt);
            t.start();
        }
    }
}

忘了,大概是这样;
要求并发调用call2的线程数小于maxCounter(也即3),请问如何添加代码(在call1中)?

解决方案

如果你了解信号量的实现机制,那么这道题目也是一个意思。

public class Test {

    private final Integer maxCounter = 3;
    private Integer current = 0;

    public void call1() {
        //在这里补充代码
        synchronized (this) {
            try {
                while (current.equals(maxCounter)) { // 请求 到达上限
                    wait();
                }
            } catch (InterruptedException ex) {
            }
            current++;
            notifyAll();
        }

        call2(current);

        synchronized (this) {
            try {
                while (current == 0) {
                    wait();
                }
            } catch (InterruptedException ex) {
            }
            current--;
            notifyAll();
        }
    }

    private void call2(Integer current) {

        System.out.println(Thread.currentThread().getName() + ": I'm called " + current);

        // 下面的休眠 2 秒钟用于测试
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ex) {
            ex.printStackTrace(System.err);
        }
    }

    static class TestThread implements Runnable {

        private Test t;

        public TestThread(Test t) {
            this.t = t;
        }

        @Override
        public void run() {
            t.call1();
        }
    }

    public static void main(String[] args) {
        Test t1 = new Test();
        TestThread tt = new TestThread(t1);
        for (int i = 0; i < 10; i++) {
            Thread t = new Thread(tt, "Thread-" + i);
            t.start();
        }
    }
}

运行这段代码,你可以发现每 2 秒内,最多只有 3 (maxCounter)个线程在运行。

这篇关于java - 控制并发线程数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆